Balancing a Tree

아직 제출이 없습니다시간 제한2초메모리 제한1024 MB

문제

Farmer John has conducted an extensive study of the evolution of different cow breeds. The result is a rooted tree with NN (2N1052\le N\le 10^5) nodes labeled 1N1\ldots N, each node corresponding to a cow breed. For each i\[2,N]i\in \[2,N], the parent of node ii is node p_ip\_i (1p_i\<i1\le p\_i\<i), meaning that breed ii evolved from breed p_ip\_i. A node jj is called an ancestor of node ii if j=p_ij=p\_i or jj is an ancestor of p_ip\_i.

Every node ii in the tree is associated with a breed having an integer number of spots s_is\_i. The "imbalance" of the tree is defined to be the maximum of s_is_j|s\_i-s\_j| over all pairs of nodes (i,j)(i,j) such that jj is an ancestor of ii.

Farmer John doesn't know the exact value of s_is\_i for each breed, but he knows lower and upper bounds on these values. Your job is to assign an integer value of s_i\[l_i,r_i]s\_i \in \[l\_i,r\_i] (0l_ir_i1090\le l\_i\le r\_i\le 10^9) to each node such that the imbalance of the tree is minimized.

입력

The first line contains TT (1T101\le T\le 10), the number of independent test cases to be solved, and an integer B0,1B\in \\{0,1\\}.

Each test case starts with a line containing NN, followed by N1N-1 integers p_2,p_3,,p_Np\_2,p\_3,\ldots,p\_N.

The next NN lines each contain two integers l_il\_i and r_ir\_i.

It is guaranteed that the sum of NN over all test cases does not exceed 10510^5.

출력

For each test case, output one or two lines, depending on the value of BB.

The first line for each test case should contain the minimum imbalance.

If B=1,B=1, then print an additional line with NN space-separated integers s_1,s_2,,s_Ns\_1,s\_2,\ldots, s\_N containing an assignment of spots that achieves the above imbalance. Any valid assignment will be accepted.