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

#LCA0000046. Khoảng cách trên cây có trọng số (Distance in the Tree)

HỌC THEO LỘ TRÌNH

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

1 lộ trình

Khoảng cách trên cây có trọng số (Distance in the Tree)

Distance in the Tree

Source: Timus

Version: Phuoc Hung OJ Extended

Problem Statement

An undirected weighted tree contains nn vertices numbered 00 through n−1n-1. Edge weights are nonnegative integers.

For every queried pair of vertices, calculate the sum of edge weights along their unique path. The distance from a vertex to itself is 00.

Input

  • The first line contains nn.
  • Next n−1n-1 lines contain u,v,wu,v,w: edge endpoints and weight.
  • The next line contains the number of queries qq.
  • The last qq lines contain pairs a,ba,b.

Output

Print one integer per query on its own line.

Subtasks

General constraints: 1≤n≤500001\le n\le 50000; 1≤q≤750001\le q\le75000; 0≤u,v,a,b<n0\le u,v,a,b<n; 0≤w≤10000\le w\le1000.

  • Subtask 1 (20 points): 1≤n≤401\le n\le 40; 1≤q≤501\le q\le 50.

  • Subtask 2 (30 points): 1≤n≤10001\le n\le 1000; 1≤q≤10001\le q\le 1000.

  • Subtask 3 (50 points): 1≤n≤500001\le n\le 50000; 1≤q≤750001\le q\le 75000.

Examples

Input

3
1 0 1
2 0 1
3
0 1
0 2
1 2

Output

1
1
2

Explanation

The edges 0−10-1 and 0−20-2 both have length 11. The first two distances equal 11. The path 1−0−21-0-2 contains both edges and has length 22.