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
1 lộ trìnhBài tập thuộc lộ trình
Mục lục đề ⌄
Đang đọc
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 vertices numbered through is rooted at vertex 1. Vertex has a fixed integer weight . Each query asks for the sum of vertex weights on the unique simple path from to , including both endpoints. If , the answer is .
Input
- The first line contains two integers , the number of vertices and the number of queries.
- The second line contains exactly integers , the weights in vertex order.
- Each of the next lines contains two integers , the endpoints of an edge.
- Each of the final lines contains two integers , the endpoints of the path whose sum is requested.
Output
Print integers, one per line, in query order.
Subtasks
- Subtask 1 (20 points): , , , . The edges form an undirected tree; all data are integers. Additionally: .
- Subtask 2 (30 points): , , , . 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): , , , . 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 . Path 4–2–5 has sum . Path 2–2 consists only of vertex 2, giving . Path 1–2–5 has sum .
Example 2
Input
1 1
-9
1 1
Output
-9
Explanation
Query contains only vertex 1, whose weight is .