#P3894. [GDOI2014] 传送

[GDOI2014] 传送

Description

There are nn countries, numbered from 00 to n1n-1. The ii-th country contains mim_i cities, numbered from 00 to mi1m_{i}-1, where the city numbered 00 is the capital. For convenience, we use (i,j)(i,j) to denote the jj-th city of the ii-th country. The cities within the same country are connected by roads that form a tree, with the capital as the root. There are no roads between cities of different countries; you can only travel via teleportation portals. In each country, only cities that are leaf nodes have teleportation portals, and the destination can be any leaf city in a country with an adjacent index. Each teleport takes 11 unit of time, and each teleportation portal can be used only once. As shown in the figure below, if the starting point is (0,2)(0,2) and the destination is (2,1)(2,1), then $(0,2)\rightarrow(1,1)\rightarrow(1,0)\rightarrow(1,2)\rightarrow(2,1)$ is a feasible path, while (0,2)(1,1)(2,1)(0,2)\rightarrow(1,1)\rightarrow(2,1) is invalid, because the portal of (1,1)(1,1) was used once in (0,2)(1,1)(0,2)\rightarrow(1,1) and again in (1,1)(2,1)(1,1)\rightarrow(2,1).

Given the starting point and the destination, find the minimum time required.

Input Format

The first line contains a positive integer nn.

Then there are nn blocks, each describing one country. The first line of each block is a positive integer mim_i, indicating that the country with index ii contains mim_i cities. Then follow mi1m_{i}-1 lines, each containing three integers u,v,tu, v, t, meaning there is a road between city uu and city vv, and the time cost is tt (1t1031 \leq t \leq 10^{3}).

The next line contains a positive integer qq, the number of queries. Each of the next qq lines contains four integers s0,s1,e0,e1s_0, s_1, e_0, e_1, where (s0,s1)(s_0, s_1) is the starting point and (e0,e1)(e_0, e_1) is the destination.

Output Format

Output qq lines, each containing a single integer. If the destination is reachable from the starting point, output the minimum time; otherwise, output 1-1.

5
3
0 1 1
0 2 1
3
0 1 2
2 0 1
3
0 1 1
0 2 1
2
0 1 2
3
0 1 1
0 2 1
3
0 2 2 1
0 0 2 1
2 2 4 1

5
6
-1

Hint

For 40%40\% of the testdata, n10,mi103,q10n \leq 10, \sum m_i \leq 10^{3}, q \leq 10.

For 60%60\% of the testdata, n103,mi106n \leq 10^{3}, \sum m_i \leq 10^{6}.

For 100%100\% of the testdata, $n \leq 3.5 \times 10^{5}, \sum m_i \leq 10^{6}, 1 \leq t \leq 10^{3}, q \leq 10^{5}$.

Translated by ChatGPT 5