#P9058. [Ynoi2004] rpmtdq

[Ynoi2004] rpmtdq

Problem Description

Given an unrooted tree with edge weights, you need to answer some queries.

Define dist(i,j)\texttt{dist(i,j)} as the distance between node ii and node jj on the tree.

For each query, you are given l,rl, r. You need to output min(dist(i,j))\min(\texttt{dist(i,j)}) where li<jrl \le i < j \le r.

Input Format

The first line contains an integer nn, denoting the number of nodes in the tree.

The next n1n - 1 lines each contain three integers x,y,zx, y, z, representing a tree edge connecting xx and yy with weight zz. The input is guaranteed to form a tree.

Then there is a line containing an integer qq, denoting the number of queries.

The next qq lines each contain two integers l,rl, r, representing a query. If for a query, there is no pair (i,j)(i, j) satisfying li<jrl \le i < j \le r, output 1-1.

Output Format

Output qq lines. Each line contains one integer, denoting the answer to the corresponding query.

5
1 2 5
1 3 3
1 4 4
3 5 2
5
1 1
1 4
2 4
3 4
2 5
-1
3
7
7
2

Hint

Idea: nzhtl1477, Solution: Kubic&ccz181078, Code: Kubic, Data: Kubic.

For 100%100\% of the testdata, n2×105n \le 2 \times 10^5, q106q \le 10^6, and 1z1091 \le z \le 10^9.

Translated by ChatGPT 5