Dona Minhoca

On a cactus graph, for each query (entry chamber, worm length) decide whether a closed non-backtracking walk of length at most M exists and give the shortest such distance.

Hard8GraphDFSDynamic programmingImplementationNo attempts yetTime limit2sMemory limit512 MB

Problem

Dona Minhoca gets furious when she hears people say that worms are palindromic animals whose head cannot be told apart from their tail.

Dona Minhoca lives in a cave built from chambers and tunnels. Each tunnel joins two distinct chambers and can be used in both directions. Take distinct chambers s1,s2,,sns_1, s_2, \dots, s_n with n3n \ge 3 and set sn+1=s1s_{n+1} = s_1. If (si,si+1)(s_i, s_{i+1}) is a tunnel for every 1in1 \le i \le n, that sequence is a cycle. The cave may contain cycles, but each chamber belongs to at most one cycle. The chambers and the tunnels are narrow. While part of Dona Minhoca's body occupies a chamber or a tunnel, there is no room for her to enter that chamber or that tunnel again.

Some chambers of the cave can be reached from the surface. Dona Minhoca has a map that gives the length of every tunnel and the two chambers it joins, and she knows her own length.

Dona Minhoca wants to enter the cave through a chamber that reaches the surface, travel as short a distance as possible inside the cave, and come out again through the chamber she entered, always moving forward and never backing up. For each query, decide whether such a trip exists, and when it does, report the shortest distance she travels inside the cave.

Input

The first line contains the number of chambers SS and the number of tunnels TT (2S1042 \le S \le 10^4, 1T2S1 \le T \le 2S). The chambers are identified by the integers 11 through SS.

Each of the next TT lines describes one tunnel with three integers AA, BB and CC (1A<BS1 \le A < B \le S, 1C1001 \le C \le 100). AA and BB are the two chambers the tunnel joins and CC is the length of the tunnel. A chamber is joined by tunnels to at most 100 other chambers, and each pair of chambers is joined by at most one tunnel. The cave is not necessarily connected.

The next line contains the number of queries QQ (1Q1001 \le Q \le 100). Each of the next QQ lines describes one query with two integers XX and MM (1XS1 \le X \le S, 1M1051 \le M \le 10^5), where XX is the chamber Dona Minhoca wants to enter through and MM is her length.

Output

For each query print one line with a single integer, the shortest distance Dona Minhoca has to travel inside the cave to enter through the chamber given in the query and come out through the same chamber without ever backing up. If entering and coming out without backing up is impossible, print -1.