Problem 177
All Pairs Shortest Distance Queries
Medium · 20 pts · Graph, Shortest Path, Floyd-Warshall
Problem
You are given an undirected weighted graph with N nodes and M edges, followed by Q queries. Each query asks for the shortest distance between nodes u and v. Print the answer to each query on its own line, or -1 if u and v are not connected. The distance from a node to itself is 0. With up to 100,000 queries, it pays to compute all distances once. N is at most 300, so the Floyd-Warshall algorithm (O(N³)) fits: for every middle node k, try to improve each distance d[i][j] with d[i][k] + d[k][j].
Input
First line: integers N (nodes, labelled 1..N) and M (edges). Next M lines: an edge u v w with weight w. Next line: integer Q. Next Q lines: a query u v.
Output
Print the answer to each query on its own line.
Constraints
1 <= N <= 300; 0 <= M <= 10000; 1 <= w <= 100000; 1 <= Q <= 100000
Example input
3 3 1 2 3 2 3 4 1 3 10 2 1 3 2 2
Example output
7 0
Explanation
From 1 to 3, the direct edge costs 10, but going through node 2 costs 3 + 4 = 7. The second query asks for the distance from 2 to itself, which is 0. So the answers are 7 and 0.