#FT0000191. Truy vấn khoảng cách trên cây (Distance Queries on a Tree)
Bài tập thuộc lộ trình
Mục lục đề ⌄
Truy vấn khoảng cách trên cây (Distance Queries on a Tree)
Distance Queries on a Tree (Truy vấn khoảng cách trên cây)
Source: AtCoder – ABC294 G Original statement: https://atcoder.jp/contests/abc294/tasks/abc294_g Version: Phuoc Hung OJ; same problem semantics and maximum source limits, with educational subtasks.
Problem Statement
Given a weighted undirected tree whose edges are indexed 1 through N-1 in input order, process 1 i w, assigning weight w to the i-th edge, and 2 u v, asking for the sum of edge weights along the unique simple path from u to v. Vertices u and v may coincide, in which case the distance is zero.
Input
Line 1: N; next N-1 lines: indexed edges u v w; next line: Q; then Q commands 1 i w or 2 u v.
Output
For each query operation, print exactly one integer on its own line in query order. Updates produce no output. Some sums exceed 32-bit integers; use signed 64-bit integers.
Subtasks
- Subtask 1 (20 points): ; ; ; the N vertices form an undirected tree with N-1 edges;
1 i whas (only when N>1);2 u vhas ; at least one type-2 query. - Subtask 2 (30 points): ; ; ; the N vertices form an undirected tree with N-1 edges;
1 i whas (only when N>1);2 u vhas ; at least one type-2 query. - Subtask 3 (50 points): ; ; ; the N vertices form an undirected tree with N-1 edges;
1 i whas (only when N>1);2 u vhas ; at least one type-2 query.
Example 1
Input
5
1 2 3
1 3 6
1 4 9
4 5 10
4
2 2 3
2 1 5
1 3 1
2 1 5
Output
9
19
11
Explanation
The path 2–1–3 weighs , while path 1–4–5 weighs . Updating edge 3 from weight 9 to 1 changes the latter distance to .
Operation-by-operation trace
2 2 3: path2–1–3, edge weights3+6; print 9.2 1 5: path1–4–5, edge weights9+10; print 19.1 3 1: edge #3 changes weight 9 → 1.2 1 5: path1–4–5, edge weights1+10; print 11.
Example 2
Input
3
1 2 5
2 3 9
5
2 1 3
1 2 2
2 1 3
2 2 2
2 1 2
Output
14
7
0
5
Explanation
Initially 1–2–3 has weight . Assigning weight 2 to edge 2 changes this to . A vertex has distance 0 to itself, while path 1–2 remains length 5.
Operation-by-operation trace
2 1 3: path1–2–3, edge weights5+9; print 14.1 2 2: edge #2 changes weight 9 → 2.2 1 3: path1–2–3, edge weights5+2; print 7.2 2 2: path2, edge weights0; print 0.2 1 2: path1–2, edge weights5; print 5.