#P3894. [GDOI2014] 传送
[GDOI2014] 传送
Description
There are countries, numbered from to . The -th country contains cities, numbered from to , where the city numbered is the capital. For convenience, we use to denote the -th city of the -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 unit of time, and each teleportation portal can be used only once. As shown in the figure below, if the starting point is and the destination is , then $(0,2)\rightarrow(1,1)\rightarrow(1,0)\rightarrow(1,2)\rightarrow(2,1)$ is a feasible path, while is invalid, because the portal of was used once in and again in .

Given the starting point and the destination, find the minimum time required.
Input Format
The first line contains a positive integer .
Then there are blocks, each describing one country. The first line of each block is a positive integer , indicating that the country with index contains cities. Then follow lines, each containing three integers , meaning there is a road between city and city , and the time cost is ().
The next line contains a positive integer , the number of queries. Each of the next lines contains four integers , where is the starting point and is the destination.
Output Format
Output lines, each containing a single integer. If the destination is reachable from the starting point, output the minimum time; otherwise, output .
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 of the testdata, .
For of the testdata, .
For 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
京公网安备 11011102002149号