1968: [USACO 2022 US Open Contest Gold] Problem 3. Balancing a Tree

文件提交:无需freopen 内存限制:512 MB 时间限制:10.000 S
评测方式:普通裁判 命题人:
提交:27 解决:0

题目描述

Farmer John has conducted an extensive study of the evolution of different cow breeds. The result is a rooted tree with N (2N105) nodes labeled 1N, each node corresponding to a cow breed. For each i[2,N], the parent of node i is node pi (1pi<i), meaning that breed i evolved from breed pi. A node j is called an ancestor of node i if j=pi or j is an ancestor of pi.

Every node i in the tree is associated with a breed having an integer number of spots si. The "imbalance" of the tree is defined to be the maximum of|sisj| over all pairs of nodes (i,j) such that j is an ancestor of i.

Farmer John doesn't know the exact value of si for each breed, but he knows lower and upper bounds on these values. Your job is to assign an integer value of si[li,ri] (0liri109) to each node such that the imbalance of the tree is minimized.

输入

The first line contains T (1T10), the number of independent test cases to be solved, and an integer B{0,1}.

Each test case starts with a line containing N, followed by N1 integers p2,p3,,pN.

The next N lines each contain two integers li and ri.

It is guaranteed that the sum of N over all test cases does not exceed 105.

输出

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

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

If B=1, then print an additional line with N space-separated integers s1,s2,,sN containing an assignment of spots that achieves the above imbalance. Any valid assignment will be 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

提示

For the first test case, the minimum imbalance is 3. One way to achieve imbalance  is to set [s1,s2,s3]=[4,1,7].

SAMPLE INPUT:

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

SAMPLE OUTPUT:

3

3 1 6

1

6 5 5 5 5

4

5 1 9

This input is the same as the first one aside from the value of . Another way to achieve imbalance 3 is to set [s1,s2,s3]=[3,1,6].

SCORING:

  • Test cases 3-4 satisfy li=ri for all i.
  • Test cases 5-6 satisfy pi=i1 for all i.
  • Test cases 7-16 satisfy no additional constraints.

Within each subtask, the first half of the test cases will satisfy B=0, and the rest will satisfy B=1.

来源/分类