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

#FT0000191. Truy vấn khoảng cách trên cây (Distance Queries on a Tree)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

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): 1≤N≤301\le N\le 30; 1≤Q≤1001\le Q\le 100; 1≤wi,w≤1091\le w_i,w\le10^9; the N vertices form an undirected tree with N-1 edges; 1 i w has 1≤i<N1\le i<N (only when N>1); 2 u v has 1≤u,v≤N1\le u,v\le N; at least one type-2 query.
  • Subtask 2 (30 points): 1≤N≤30001\le N\le 3000; 1≤Q≤40001\le Q\le 4000; 1≤wi,w≤1091\le w_i,w\le10^9; the N vertices form an undirected tree with N-1 edges; 1 i w has 1≤i<N1\le i<N (only when N>1); 2 u v has 1≤u,v≤N1\le u,v\le N; at least one type-2 query.
  • Subtask 3 (50 points): 1≤N≤2000001\le N\le 200000; 1≤Q≤2000001\le Q\le 200000; 1≤wi,w≤1091\le w_i,w\le10^9; the N vertices form an undirected tree with N-1 edges; 1 i w has 1≤i<N1\le i<N (only when N>1); 2 u v has 1≤u,v≤N1\le u,v\le N; 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 3+6=93+6=9, while path 1–4–5 weighs 9+10=199+10=19. Updating edge 3 from weight 9 to 1 changes the latter distance to 1+10=111+10=11.

Operation-by-operation trace

  1. 2 2 3: path 2–1–3, edge weights 3+6; print 9.
  2. 2 1 5: path 1–4–5, edge weights 9+10; print 19.
  3. 1 3 1: edge #3 changes weight 9 → 1.
  4. 2 1 5: path 1–4–5, edge weights 1+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 5+9=145+9=14. Assigning weight 2 to edge 2 changes this to 5+2=75+2=7. A vertex has distance 0 to itself, while path 1–2 remains length 5.

Operation-by-operation trace

  1. 2 1 3: path 1–2–3, edge weights 5+9; print 14.
  2. 1 2 2: edge #2 changes weight 9 → 2.
  3. 2 1 3: path 1–2–3, edge weights 5+2; print 7.
  4. 2 2 2: path 2, edge weights 0; print 0.
  5. 2 1 2: path 1–2, edge weights 5; print 5.