PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN
#PS0000296. Tổng cây con tĩnh (Static Subtree 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 cây con tĩnh (Static Subtree Sum)
Static Subtree 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 . For every query vertex , sum the weights of all its descendants including itself. No weights change.
The subtree rooted at includes and every vertex whose path from root 1 passes through .
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 one integer , the root of the subtree 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
1
2
3
5
Output
11
4
4
-1
Explanation
For query 1 the entire tree sums to . The subtree of 2 contains vertices 2, 4, 5, giving . Vertices 3 and 5 are leaves, so the last two answers are 4 and .
Example 2
Input
1 2
-9
1
1
Output
-9
-9
Explanation
Both queries refer to the subtree of vertex 1, consisting of a single vertex of weight . Print twice.