Tree
Time limit2sMemory limit1024 MB
Given a rooted weighted tree, find the minimum total of |C[i]| times W[i] so that every subtree coefficient sum lies between L and R.
- Level
Hard9 of 10
- Topics
- Tree, Dynamic programming, Greedy
- Solved
- No attempts yet
Problem
Consider a tree with vertices, numbered from to . Vertex is the root. Every vertex except the root has exactly one parent. For each with , the parent of vertex is , where . We also set .
For any vertex (), the subtree of is the set containing , every vertex whose parent is , every vertex whose grandparent is , every vertex whose great-grandparent is , and so on.
The figure below shows an example tree with vertices. Each arrow connects a vertex to its parent, except for the root, which has no parent. The subtree of vertex 2 contains vertices 2, 3, 4 and 5. The subtree of vertex 0 contains all 6 vertices, and the subtree of vertex 4 contains only vertex 4.

Each vertex has a nonnegative integer weight. The weight of vertex is .
You must answer queries. Each query is a pair of positive integers , and the answer is computed as follows.
Assign an integer coefficient to each vertex. The assignment is a sequence , where is the coefficient of vertex . Call this sequence a coefficient sequence. Coefficients may be negative, zero, or positive.
For a query , a coefficient sequence is valid if, for every vertex (), the sum of the coefficients over the subtree of is at least and at most .
For a coefficient sequence, the cost of vertex is . The total cost is the sum of the costs of all vertices. For each query, output the minimum total cost over all valid coefficient sequences.
It can be shown that every query has at least one valid coefficient sequence.
Constraints
- for each with
- for each with
- in each query