Tree

시간 제한2초메모리 제한1024 MB

요약
각 질의 (L,R)마다 모든 부분트리 합이 [L,R]에 들어가도록 정수 계수를 배정하고, 계수 절댓값의 가중합을 최소로 만든다.
난이도

어려움10점 중 9점

유형
트리, 동적 계획법, 그리디, 수학
정답자
아직 제출이 없습니다

문제

Consider a tree consisting of NN vertices, numbered from 00 to N−1N - 1. Vertex 00 is called the root. Every vertex, except for the root, has a single parent. For every ii, such that 1≤i<N1 ≤ i < N, the parent of vertex ii is vertex P\[i]P\[i], where P\[i]<iP\[i] < i. We also assume P\[0]=−1P\[0] = -1.

For any vertex ii (0≤i<N0 ≤ i < N), the subtree of ii is the set of the following vertices:

  • ii,
  • and any vertex whose parent is ii,
  • and any vertex whose parent's parent is ii,
  • and any vertex whose parent's parent's parent is ii, and etc.

The picture below shows an example tree consisting of N=6N = 6 vertices. Each arrow connects a vertex to its parent, except for the root, which has no parent. The subtree of vertex 22 contains vertices 22, 33, 44 and 55. The subtree of vertex 00 contains all 66 vertices of the tree and the subtree of vertex 44 contains only vertex 44.

Each vertex is assigned a nonnegative integer weight. We denote the weight of vertex ii (0≤i<N0 ≤ i < N) by W\[i]W\[i].

Your task is to write a program that will answer QQ queries, each specified by a pair of positive integers (L,R)(L,R). 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 C\[0],…,C\[N−1]C\[0],\dots ,C\[N - 1], where C\[i]C\[i] (0≤i<N0 ≤ i < N) is the coefficient assigned to vertex ii. Let us call this sequence a coefficient sequence. Note that the elements of the coefficient sequence can be negative, 00, or positive.

For a query (L,R)(L,R), a coefficient sequence is called valid if, for every vertex ii (0≤i<N0 ≤ i < N), the following condition holds: the sum of the coefficients of the vertices in the subtree of vertex ii is not less than LL and not greater than RR.

For a given coefficient sequence C\[0],…,C\[N−1]C\[0],\dots ,C\[N - 1], the cost of a vertex ii is ∣C\[i]∣⋅W\[i]|C\[i]| \cdot W\[i], where ∣C\[i]∣|C\[i]| denotes the absolute value of C\[i]C\[i]. 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.

제한

  • 1≤N≤200,0001 ≤ N ≤ 200\\, 000
  • 1≤Q≤100,0001 ≤ Q ≤ 100\\, 000
  • P\[0]=−1P\[0] = -1
  • 0≤P\[i]<i0 ≤ P\[i] < i for each ii such that 1≤i<N1 ≤ i < N
  • 0≤W\[i]≤1,000,0000 ≤ W\[i] ≤ 1\\, 000\\, 000 for each ii such that 0≤i<N0 ≤ i < N
  • 1≤L≤R≤1,000,0001 ≤ L ≤ R ≤ 1\\, 000\\, 000 in each query

예제

이 문제는 공개된 예제가 없습니다.