atcoder#ARC160E. [ARC160E] Make Biconnected

[ARC160E] Make Biconnected

Score : 800800 points

Problem Statement

You are given an undirected tree GG with NN vertices. The degree of every vertex in G is at most 3. The vertices are numbered 11 to NN. The edges are numbered 11 to N1N-1, and edge ii connects vertex uiu_i and vertex viv_i. Each vertex has a fixed weight, and the weight of vertex ii is WiW_i.

You will add zero or more edges to GG. The cost of adding an edge between vertex ii and vertex jj is Wi+WjW_i + W_j.

Print one way to add edges to satisfy the following condition for the minimum possible total cost.

  • GG is 22-vertex-connected. In other words, for every vertex vv in GG, removing vv and its incident edges from GG would not disconnect GG.

You have TT test cases to solve.

Constraints

  • 1T2×1051 \leq T \leq 2 \times 10^5
  • 3N2×1053 \leq N \leq 2 \times 10^5
  • 1ui,viN1 \leq u_i, v_i \leq N
  • The given graph is a tree.
  • The degree of every vertex in the given graph is at most 33.
  • 1Wi1091 \leq W_i \leq 10^9
  • WiW_i is an integer.
  • The sum of NN across the test cases is at most 2×1052 \times 10^5.

Input

The input is given from Standard Input in the following format, where casei\mathrm{case}_i represents the ii-th test case:

TT

case1\mathrm{case}_1

case2\mathrm{case}_2

\vdots

caseN\mathrm{case}_N

Each test case is in the following format:

NN

W1W_1 W2W_2 \dots WNW_N

u1u_1 v1v_1

u2u_2 v2v_2

\vdots

uN1u_{N-1} vN1v_{N-1}

Output

For each test case, print a solution in the following format, where:

  • MM is the number of added edges, and
  • the ii-th added edge connects vertex aia_i and vertex bib_i.

If multiple solutions exist, any of them would be accepted.

MM

a1a_1 b1b_1

a2a_2 b2b_2

\vdots

aMa_M bMb_M

2
3
2 3 5
1 2
2 3
7
1 10 100 1000 10000 100000 1000000
1 2
2 3
2 4
3 5
3 6
4 7
1
1 3
2
7 6
1 5

In the first test case, adding an edge connecting vertex 11 and vertex 33 makes GG satisfy the condition in the problem statement. The cost of this is W1+W3=2+5=7W_1 + W_3 = 2 + 5 = 7. There is no way to add edges to satisfy the condition for a cost of less than 77, so this is a valid solution.

In the second test case, the solution above has a total cost of $(W_7 + W_6) + (W_1 + W_5) = 1100000 + 10001 = 1110001$, which is the minimum possible.