#SRD0000099. Tích vô hướng trên đường tổ tiên (Tree Master)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Tích vô hướng trên đường tổ tiên (Tree Master)
Tree Master
Source: Codeforces
Version: Phuoc Hung OJ Extended
Problem Statement
You are given a tree with vertices rooted at , numbered to . Vertex has a positive integer weight . For , its direct parent is ; define .
Two query vertices always have the same depth, defined as the number of edges from the root. Define by the following process:
- Set .
- While both and are nonzero, add to , then simultaneously set and .
- Once both vertices reach the artificial vertex , return .
For each of the queries containing , compute . The two vertices may coincide, in which case the products are squares of weights along the path to the root.
Input
The first line contains . The second line contains . The third line contains . Each of the next lines contains two vertices of equal depth.
Output
For each query, print the integer on its own line. Results may exceed 32-bit signed range.
Subtasks
- Subtask 1 (10 points): , .
- Subtask 2 (20 points): , .
- Subtask 3 (30 points): , .
- Subtask 4 (40 points): , .
Conditions shared by all subtasks: For every group: , , , for , , and .
Examples
Example 1
Input
6 2
1 5 2 3 1 1
1 2 3 3 2
4 5
6 6
Output
33
27
Explanation
For , the ancestor chains are and . The sum is . For it is .
Example 2
Input
14 8
3 2 5 3 1 4 2 2 2 5 5 5 2 4
1 2 3 1 1 4 7 3 3 1 5 3 8
4 4
4 10
13 10
3 12
13 9
3 12
9 10
11 5
Output
47
53
48
36
42
36
48
14
Explanation
Example 2 contains repeated queries, including twice, with answer both times. A query does not modify any tree data.