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

#PS0000297. Tổng trọng số đường đi tĩnh (Static Vertex-weighted Path Sum)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Tổng trọng số đường đi tĩnh (Static Vertex-weighted Path Sum)

Static Vertex-weighted Path Sum

Source: Phước Hưng OJ

Version: Phuoc Hung OJ Extended

Problem Statement

An undirected tree with NN vertices numbered 11 through NN is rooted at vertex 1. Vertex vv has a fixed integer weight ava_v. Each query (u,v)(u,v) asks for the sum of vertex weights on the unique simple path from uu to vv, including both endpoints. If u=vu=v, the answer is aua_u.

Input

  • The first line contains two integers N,QN,Q, the number of vertices and the number of queries.
  • The second line contains exactly NN integers a1,…,aNa_1,\ldots,a_N, the weights in vertex order.
  • Each of the next N−1N-1 lines contains two integers x,yx,y, the endpoints of an edge.
  • Each of the final QQ lines contains two integers u,vu,v, the endpoints of the path whose sum is requested.

Output

Print QQ integers, one per line, in query order.

Subtasks

  • Subtask 1 (20 points): 1≤N,Q≤2000001\le N,Q\le200000, ∣av∣≤109|a_v|\le10^9, 1≤x,y≤N1\le x,y\le N, 1≤u,v≤N1\le u,v\le N. The edges form an undirected tree; all data are integers. Additionally: N≤30,Q≤40N\le30, Q\le40.
  • Subtask 2 (30 points): 1≤N,Q≤2000001\le N,Q\le200000, ∣av∣≤109|a_v|\le10^9, 1≤x,y≤N1\le x,y\le N, 1≤u,v≤N1\le u,v\le N. The edges form an undirected tree; all data are integers. Additionally: the tree is a simple path (each vertex has degree at most 2).
  • Subtask 3 (50 points): 1≤N,Q≤2000001\le N,Q\le200000, ∣av∣≤109|a_v|\le10^9, 1≤x,y≤N1\le x,y\le N, 1≤u,v≤N1\le u,v\le N. The edges form an undirected tree; all data are integers.

Example 1

Input

5 4
3 -2 4 7 -1
1 2
1 3
2 4
2 5
4 3
4 5
2 2
1 5

Output

12
4
-2
0

Explanation

Path 4–2–1–3 has sum 7−2+3+4=127-2+3+4=12. Path 4–2–5 has sum 7−2−1=47-2-1=4. Path 2–2 consists only of vertex 2, giving −2-2. Path 1–2–5 has sum 3−2−1=03-2-1=0.

Example 2

Input

1 1
-9
1 1

Output

-9

Explanation

Query (1,1)(1,1) contains only vertex 1, whose weight is −9-9.