Tree
문제
Consider a tree consisting of vertices, numbered from to . Vertex is called the root. Every vertex, except for the root, has a single parent. For every , such that 1 ≤ i < N, the parent of vertex is vertex , where . We also assume .
For any vertex (0 ≤ i < N), the subtree of is the set of the following vertices:
- ,
- and any vertex whose parent is ,
- and any vertex whose parent's parent is ,
- and any vertex whose parent's parent's parent is , and etc.
The picture below shows an example tree consisting of vertices. Each arrow connects a vertex to its parent, except for the root, which has no parent. The subtree of vertex contains vertices , , and . The subtree of vertex contains all vertices of the tree and the subtree of vertex contains only vertex .
Each vertex is assigned a nonnegative integer weight. We denote the weight of vertex (0 ≤ i < N) by .
Your task is to write a program that will answer queries, each specified by a pair of positive integers . The answer to the query should be computed as follows.
Consider assigning an integer, called a coefficient, to each vertex of the tree. Such an assignment is described by a sequence , where (0 ≤ i < N) is the coefficient assigned to vertex . Let us call this sequence a coefficient sequence. Note that the elements of the coefficient sequence can be negative, , or positive.
For a query , a coefficient sequence is called valid if, for every vertex (0 ≤ i < N), the following condition holds: the sum of the coefficients of the vertices in the subtree of vertex is not less than and not greater than .
For a given coefficient sequence , the cost of a vertex is , where denotes the absolute value of . Finally, the total cost is the sum of the costs of all vertices. Your task is to compute, for each query, the minimum total cost that can be attained by some valid coefficient sequence.
It can be shown that for any query, at least one valid coefficient sequence exists.