problems / 206

Tree Path Queries

medium lca trees binary-search prefix-sums 2000 ms · 256 MB

Tree Path Queries

You are given a tree with n nodes (numbered 1 to n). Each node i has an integer value value[i]. The tree is rooted at node 1.

You must handle q queries of two types:

  1. LCA query: Given two nodes u and v, output their lowest common ancestor.
  2. Path sum query: Given two nodes u and v, output the sum of values of all nodes on the unique path from u to v (inclusive).

Input

The first line contains n and q (1 ≤ n ≤ 10^5, 1 ≤ q ≤ 10^5).

The second line contains n space-separated integers: value[1], value[2], ..., value[n] where -10^9 ≤ value[i] ≤ 10^9.

The next n-1 lines describe the tree edges. Line i+2 contains two integers u and v (1 ≤ u, v ≤ n), indicating an undirected edge between nodes u and v. The tree is guaranteed to be connected.

Each of the next q lines contains a query:

  • 1 u v: LCA query, output the lowest common ancestor of nodes u and v.
  • 2 u v: Path sum query, output the sum of values on the path from u to v.

Output

For each LCA query, print the node number of the lowest common ancestor.

For each path sum query, print the sum as a 64-bit signed integer.

Notes

The path from u to v includes both endpoints and all intermediate nodes on the unique path in the tree.

Constraints

  • 1 ≤ n ≤ 10^5
  • 1 ≤ q ≤ 10^5
  • -10^9 ≤ value[i] ≤ 10^9
  • Path sums fit in a 64-bit signed integer

Example 1

Input

5 5
10 20 30 40 50
1 2
1 3
2 4
2 5
1 4 5
2 4 5
1 2 3
2 1 2
2 2 5

Output

2
110
1
30
70

Example 2

Input

7 6
5 -3 8 2 -1 6 4
1 2
2 3
2 4
1 5
5 6
5 7
1 3 4
2 3 4
1 6 7
2 6 7
1 1 4
2 1 3

Output

2
7
5
9
1
10

Hints · reveal one at a time if you're stuck

Hint 1

Root the tree at node 1 and compute each node's depth and the sum of values from the root down to it. With n and q up to 10^5, walking the path for every query is too slow, so what do you need to answer a query quickly?

Hint 2

Finding the lowest common ancestor quickly is a standard technique: store, for every node, its ancestors at power-of-two distances, and jump in powers of two. Build these with an iterative traversal such as BFS so that a long chain cannot overflow the call stack.

Hint 3

Think about what the root-to-node sums count for both endpoints. Which nodes are counted twice, and how many times is the LCA counted in the result you want?

report an issue Prefer your own editor? sooks prep 206 (CLI)
Sign in to run code

Run your code on the examples, or submit it against every test.