#P3384. 【模板】重链剖分 / 树链剖分

【模板】重链剖分 / 树链剖分

Description

As stated, given a tree with NN nodes (connected and acyclic), each node stores a value. Support the following operations:

  • 1 x y z: add zz to the value of every node on the shortest path from xx to yy in the tree.
  • 2 x y: query the sum of values of all nodes on the shortest path from xx to yy in the tree.
  • 3 x z: add zz to the value of every node in the subtree rooted at xx.
  • 4 x: query the sum of values of all nodes in the subtree rooted at xx.

Input Format

The first line contains 44 positive integers N,M,R,PN, M, R, P, representing the number of nodes in the tree, the number of operations, the index of the root, and the modulus, respectively (i.e., all outputs are taken modulo this).

The next line contains NN non-negative integers, representing the initial value at each node in order.

The next N1N-1 lines each contain two integers x,yx, y, indicating an edge between nodes xx and yy (guaranteed acyclic and connected).

The next MM lines each contain several positive integers; each line represents one operation.

Output Format

Output several lines, each being the result of operation type 2 or 4 (taken modulo PP), in order.

5 5 2 24
7 3 7 8 0 
1 2
1 5
3 1
4 1
3 4 2
3 2 2
4 5
1 5 1 3
2 1 3
2
21

Hint

[Constraints]

For 30%30\% of the testdata: 1N101 \leq N \leq 10, 1M101 \leq M \leq 10.

For 70%70\% of the testdata: 1N1031 \leq N \leq {10}^3, 1M1031 \leq M \leq {10}^3.

For 100%100\% of the testdata: 1N1051 \le N \le {10}^5, 1M1051 \le M \le {10}^5, 1RN1 \le R \le N, 1P2301 \le P \le 2^{30}. All input numbers are within the int range.

[Sample Explanation]

The structure of the tree is as follows:

The operations are as follows:

Therefore, the outputs should be 22 and 2121 in order.

Translated by ChatGPT 5