#P8274. [USACO22OPEN] Balancing a Tree G

    ID: 9354 远端评测题 2000ms 256MiB 尝试: 0 已通过: 0 显示难度提高 上传者: 标签>数学贪心二分USACO2022Special Judge构造

[USACO22OPEN] Balancing a Tree G

Background

Thanks to @tiger2005 for providing the SPJ.

Problem Description

Farmer John has done extensive research on the evolution of different cow breeds. The results form a rooted tree with NN (2≤N≤1052\le N\le 10^5) nodes, numbered 1…N1\ldots N, where each node corresponds to a cow breed. For each i∈[2,N]i\in [2,N], the parent of node ii is node pip_i (1≤pi<i1\le p_i< i), meaning that breed ii evolved from breed pip_i. We call node jj an ancestor of node ii if j=pij=p_i or jj is an ancestor of pip_i.

The breed associated with node ii has an integer number of spots sis_i. Define the tree's "imbalance" as the maximum value of ∣si−sj∣|s_i-s_j| over all pairs of nodes (i,j)(i,j) where jj is an ancestor of ii.

Farmer John does not know the exact value of each sis_i, but he knows a lower bound and an upper bound for each value. Your task is to assign an integer value si∈[li,ri]s_i \in [l_i,r_i] (0≤li≤ri≤1090\le l_i\le r_i\le 10^9) to each node to minimize the imbalance of the tree.

Input Format

The first line of input contains TT (1≤T≤101\le T\le 10), the number of independent subtest cases to solve, and an integer B∈{0,1}B\in \{0,1\}.

The first line of each subtest case contains NN. The second line contains N−1N-1 integers p2,p3,…,pNp_2,p_3,\ldots,p_N.

The next NN lines each contain two integers lil_i and rir_i.

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

Output Format

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

The first line of each subtest case contains the minimum imbalance.

If B=1B=1, then output an additional line containing NN space-separated integers s1,s2,…,sNs_1,s_2,\ldots, s_N, one assignment of spot counts that achieves the above imbalance. Any valid assignment is accepted.

3 0
3
1 1
0 100
1 1
6 7
5
1 2 3 4
6 6
1 6
1 6
1 6
5 5
3
1 1
0 10
0 1
9 10
3
1
4

3 1
3
1 1
0 100
1 1
6 7
5
1 2 3 4
6 6
1 6
1 6
1 6
5 5
3
1 1
0 10
0 1
9 10
3
3 1 6
1
6 5 5 5 5
4
5 1 9

Hint

[Sample Explanation 1]

For the first subtest case, the minimum imbalance is 33. One way to achieve imbalance 33 is to set [s1,s2,s3]=[4,1,7][s_1,s_2,s_3]=[4,1,7].

[Sample Explanation 2]

This subtest case is exactly the same as the first one except for the value of BB. Another way to achieve imbalance 33 is to set [s1,s2,s3]=[3,1,6][s_1,s_2,s_3]=[3,1,6].

[Constraints]

  • Test points 3-4: for all ii, li=ril_i=r_i.
  • Test points 5-6: for all ii, pi=i−1p_i=i-1.
  • Test points 7-16: no additional constraints.

In each subtask, the first half of the test points satisfy B=0B=0, and the second half satisfy B=1B=1.

Translated by ChatGPT 5