Skip to content
UPEEC

All-Pairs Shortest Paths

Hard#graphs#floyd-warshall#shortest-path· solved by 0 · time limit 2.0 s

A directed graph has n≤300n \le 300 nodes and weighted edges. Answer qq queries: the shortest distance from aa to bb, or -1. With so few nodes, Floyd–Warshall (O(n3)O(n^3)) precomputes every answer.

Input

nn and mm, mm lines u v w (directed, there may be repeats), qq, then qq lines a b.

Output

One answer per line.

Constraints

1≤n≤3001 \le n \le 300, 1≤w≤1041 \le w \le 10^4

Sample 1

Input

3 3
1 2 4
2 3 1
1 3 10
3
1 3
3 1
2 2

Output

5
-1
0

Sign in or join free to run and submit your solution.