Under construction

Still being built. Things may change

Tree

Time limit2sMemory limit1024 MB

Summary
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 NN vertices, numbered from 00 to N−1N - 1. Vertex 00 is the root. Every vertex except the root has exactly one parent. For each ii with 1≤i<N1 \le i < N, the parent of vertex ii is P[i]P[i], where P[i]<iP[i] < i. We also set P[0]=−1P[0] = -1.

For any vertex ii (0≤i<N0 \le i < N), the subtree of ii is the set containing ii, every vertex whose parent is ii, every vertex whose grandparent is ii, every vertex whose great-grandparent is ii, and so on.

The figure below shows an example tree with N=6N = 6 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 ii is W[i]W[i].

You must answer QQ queries. Each query is a pair of positive integers (L,R)(L, R), and the answer is computed as follows.

Assign an integer coefficient to each vertex. The assignment is a sequence C[0],…,C[N−1]C[0], \dots, C[N-1], where C[i]C[i] is the coefficient of vertex ii. Call this sequence a coefficient sequence. Coefficients may be negative, zero, or positive.

For a query (L,R)(L, R), a coefficient sequence is valid if, for every vertex ii (0≤i<N0 \le i < N), the sum of the coefficients over the subtree of ii is at least LL and at most RR.

For a coefficient sequence, the cost of vertex ii is ∣C[i]∣×W[i]|C[i]| \times W[i]. 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

  • 1≤N≤2000001 \le N \le 200000
  • 1≤Q≤1000001 \le Q \le 100000
  • P[0]=−1P[0] = -1
  • 0≤P[i]<i0 \le P[i] < i for each ii with 1≤i<N1 \le i < N
  • 0≤W[i]≤10000000 \le W[i] \le 1000000 for each ii with 0≤i<N0 \le i < N
  • 1≤L≤R≤10000001 \le L \le R \le 1000000 in each query

Examples1

  1. Example 1

    Input
    1 1
    -1
    5
    3 4
    
    Expected output
    15