URI Online Judge | 1711

Miss Worm

By Ricardo Anido BR Brazil

Timelimit: 1

Miss Worm is furious when she hears people say worms are palindrome animals, for which one cannot distinguish head from tail. What an outrageous lie!

Miss Worm lives in a beautiful cave, composed of chambers and tunnels. Each tunnel connects two different chambers and can be used in both directions. A cycle in the cave is a sequence of chambers s1, s2, . . . , sn, sn+1 = s1 , where si ≠ si+1 and (si, si+1 ) is a tunnel, for 1 ≤ i ≤ n. Miss Worm’s cave may contain cycles, but each chamber is part of at most one cycle. Tunnels and caves are rather cramped, so that if some part of Miss Worm’s body is already ocuppying a tunnel or a cave, there is no room for Miss Worm to re-enter that tunnel or cave.

Some cave chambers have access from the surface. Miss Worm has a map that describes the cave, informing the length of each tunnel and which two chambers each tunnel links. Miss Worm is also self-councious and knows her exact length.

Miss Worm wants to know, for the chambers that have access to the surface, if it is possible to enter the cave by that chamber, walk the minimum possible distance inside the cave and leave the cave by the same chamber, moving always ahead, never moving backwards. Can you help her?

Input

The input contains several test cases. The first line of a test case contains two integers S (2S104 ) and T (1T2S) representing respectively the number of chambers and the number of tunnels in the cave. Chambers are identified by integers from 1 to S. Each of the next T lines describes a tunnel and contains three integers A, B and C (1A < BS; 1C100), where A and B represent the chambers connected by the tunnel, and C represents the tunnel’s length. No chamber is connected to more than 100 other chambers. The next line contains an integer Q (1Q100), which indicates the number of queries. Each of the next Q lines describes a query and contains two integers X (1XS) and M (1M105 ), indicating respectively the chamber Miss Worm wants to enter the cave and the length of Miss Worm’s body.

Output

For each query in the input your program must produce a single line, containing a single integer, the length of the shortest walk Miss Worm must tread to enter and leave the cave by the chamber indicated in the query, moving always ahead, never moving backwards. If that is not possible, the line must contain the value −1.

Sample Input Sample Output

4 4
1 2 12
2 3 10
3 4 8
2 4 5
3
1 23
4 10
1 24
8 9
1 2 1
2 3 1
3 4 1
2 5 10
5 6 25
2 6 20
3 7 9
7 8 3
3 8 4
4
1 10
4 60
8 5
7 55

47
23
-1
20
-1
16
71