ADA University - February 12 - LCA
A group of ants is really proud because they built a magnificent and large colony. However, the enormous size has become a problem, because many ants do not know the path between some parts of the colony. They desperately need your help!
The colony of ants was made as a series of n anthills, connected by tunnels. The ants, obsessive as they are, numbered the anthills sequentially as they built them. The first anthill, numbered 0, did not require any tunnel, but for each of the subsequent anthills, 1 through n − 1, the ants also built a single tunnel that connected the new anthill to one of the existing anthills. Of course, this tunnel was enough to allow any ant to go to any previously built anthill, possibly passing through other anthills in its path, so they did not bother making extra tunnels and continued building more anthills.
Your job is, given the structure of the colony and a set of queries, calculate for each query the shortest path between pairs of anthills. The length of a path is the sum of the lengths of all tunnels that need to be traveled.
Each test case is given using several lines. The first line contains the number n (2 ≤ n ≤
105) of anthills in the colony. Each of the next n − 1 lines contains two integers that describe a tunnel. Line i (1 ≤ i ≤ n − 1) contains
Li, indicating that anthill i was connected directly to anthill
Ai with a tunnel of length
Li (0 ≤
Ai ≤ i − 1 and 1 ≤
109). The next line contains the number of queries q (1 ≤ q ≤
105) that follow. Each of the next q lines describes a query and contains two distinct integers s and t (0 ≤ s, t ≤ n − 1), representing respectively the source and target anthills.
The last test case is followed by a line containing one zero.
For each test case output a single line with q integers, each of them being the length of a shortest path between the pair of anthills of a query. Write the results for each query in the same order that the queries were given in the input.
6 0 8 1 7 1 9 0 3 4 2 4 2 3 5 2 1 4 0 3 2 0 1 2 1 0 0 1 6 0 1000000000 1 1000000000 2 1000000000 3 1000000000 4 1000000000 1 5 0 0
16 20 11 17 1 1 5000000000