PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#SRD0000103. Cây con và cấp số cộng (Arithmetic Subtrees)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Cây con và cấp số cộng (Arithmetic Subtrees)

Arithmetic Subtrees

Source: DMOJ

Version: Phuoc Hung OJ Extended

Problem Statement

You are given a tree with NN vertices numbered from 00 to N−1N-1, rooted at vertex 00. For 1≤i<N1\le i<N, its parent is PiP_i where 0≤Pi<i0\le P_i<i. The depth d(v)d(v) is the number of edges from root 00; hence d(0)=0d(0)=0 and d(i)=d(Pi)+1d(i)=d(P_i)+1. All vertex values are initially 00.

Process QQ operations:

  • UPDATE u a b c: for every vertex vv in the subtree of uu with a≤d(v)≤ba\le d(v)\le b, add c⋅(d(v)−d(u))c\cdot(d(v)-d(u)) to its value. This is an increment, not an assignment.
  • QUERY u a b: output the sum of current values of vertices vv in the subtree of uu satisfying a≤d(v)≤ba\le d(v)\le b.

If no vertices qualify, including when a>ba>b, a query returns 00 and an update changes nothing.

Input

  • The first line contains N,QN,Q.
  • The next line contains N−1N-1 integers P1,P2,…,PN−1P_1,P_2,\ldots,P_{N-1}.
  • Each of the next QQ lines is either UPDATE u a b c or QUERY u a b.

Output

For each QUERY, output the required integer sum (which may need a 64-bit integer type) on its own line.

Subtasks

  • Subtask 1 (5 points): 2≤N≤10002\le N\le1000, 1≤Q≤10001\le Q\le1000; 0≤Pi<i0\le P_i<i; 0≤u,a,b≤N−10\le u,a,b\le N-1, 0≤c<10000\le c<1000.
  • Subtask 2 (10 points): 2≤N≤1052\le N\le10^5, 1≤Q≤1051\le Q\le10^5; Pi=i−1P_i=i-1 for every 1≤i<N1\le i<N (chain); 0≤u,a,b≤N−10\le u,a,b\le N-1, 0≤c<10000\le c<1000.
  • Subtask 3 (10 points): 2≤N≤1052\le N\le10^5, 1≤Q≤1051\le Q\le10^5; 0≤Pi<i0\le P_i<i; all operations satisfy a=0a=0, b=N−1b=N-1; 0≤u≤N−10\le u\le N-1, 0≤c<10000\le c<1000.
  • Subtask 4 (10 points): 2≤N≤1052\le N\le10^5, 1≤Q≤1051\le Q\le10^5; 0≤Pi<i0\le P_i<i; all operations satisfy u=0u=0; 0≤a,b≤N−10\le a,b\le N-1, 0≤c<10000\le c<1000.
  • Subtask 5 (65 points): 2≤N≤1052\le N\le10^5, 1≤Q≤1051\le Q\le10^5; 0≤Pi<i0\le P_i<i; 0≤u,a,b≤N−10\le u,a,b\le N-1, 0≤c<10000\le c<1000.

Examples

Input

5 4
0 1 1 3
UPDATE 0 1 2 397
QUERY 0 2 2
UPDATE 3 0 3 688
QUERY 1 1 3

Output

1588
2673

Explanation

The root 0 has depth 0; vertices 1, 2, 3 and 4 have depths 1, 2, 2 and 3. The first update adds 397(d(v)−0)397(d(v)-0) to vertices at depth 1 or 2, producing [0,397,794,794,0][0,397,794,794,0]. QUERY 0 2 2 adds the two depth-2 values: 794+794=1588794+794=1588. UPDATE 3 0 3 688 adds 688 only to vertex 4. The last query sums the values of vertices 1, 2, 3 and 4 in the subtree of 1: 397+794+794+688=2673397+794+794+688=2673.