Balancing a Tree
Time limit2sMemory limit1024 MB
Pick each node's spot count within its [l, r] range so that the largest gap between any node and its ancestor is as small as possible.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Binary search, Tree
- Solved
- No attempts yet
Problem
Farmer John has conducted an extensive study of the evolution of different cow breeds. The result is a rooted tree with () nodes labeled , each node corresponding to a cow breed. For each , the parent of node is node (), meaning that breed evolved from breed . A node is called an ancestor of node if or is an ancestor of . Every node in the tree is associated with a breed having an integer number of spots . The imbalance of the tree is defined to be the maximum of over all pairs of nodes such that is an ancestor of . Farmer John does not know the exact value of for each breed, but he knows lower and upper bounds on these values. Your job is to assign an integer value () to each node so that the imbalance of the tree is minimized.
Input
The first line contains (), the number of independent test cases, and an integer . Each test case starts with a line containing , followed by a line with integers . The next lines each contain two integers and . It is guaranteed that the sum of over all test cases does not exceed .
Output
For each test case, output one or two lines, depending on the value of . The first line should contain the minimum imbalance. If , print one more line with space-separated integers that achieve that imbalance. Any valid assignment is accepted.