A small country has n cities and m roads. Answer many questions of the form "what is the cheapest cost to go from city u to city v?".
What to build
Fill a matrix with a large value and 0 on the diagonal, write the road costs into it (keeping the smaller cost if a road appears twice), run the three Floyd–Warshall loops, then answer each query from the matrix.
Requirements
- Use Floyd–Warshall once, before the queries
- Print -1 when there is no route
Input
The first line has n, m and q. Then m lines a b w (roads both ways). Then q lines u v.
Output
For each query, the cheapest cost or -1, one per line.
Constraints
1 ≤ n ≤ 100. 0 ≤ m ≤ 2,000. 1 ≤ q ≤ 10,000. 1 ≤ w ≤ 10⁶.
Example
Input:
4 4 3
1 2 5
2 3 3
3 4 1
1 4 10
1 4
4 1
2 2
Output:
9
9
0
Why it works
After the loop for middle vertex k, d[i][j] is the cheapest cost using only the vertices up to k in between. After all n rounds it is the true shortest distance. The cost is n³ = 10⁶ steps, and each query is a lookup.
Examples
4 4 3 1 2 5 2 3 3 3 4 1 1 4 10 1 4 4 1 2 2
9 9 0
3 1 2 1 2 7 1 3 2 1
-1 7
Hints
Hint 1
const long long INF = 1000000000000LL; vector<vector<long long> > d(n + 1, vector<long long>(n + 1, INF));
Hint 2
Loop k first, then i, then j: d[i][j] = min(d[i][j], d[i][k] + d[k][j]).
Hint 3
Print -1 when d[u][v] is still INF.
Solution
Show one correct solution (try it yourself first)
#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n, m, q;
cin >> n >> m >> q;
const long long INF = 1000000000000LL;
vector<vector<long long> > d(n + 1, vector<long long>(n + 1, INF));
for (int i = 1; i <= n; i++) d[i][i] = 0;
for (int i = 0; i < m; i++) {
int a, b;
long long w;
cin >> a >> b >> w;
d[a][b] = min(d[a][b], w);
d[b][a] = min(d[b][a], w);
}
for (int k = 1; k <= n; k++)
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n; j++)
if (d[i][k] + d[k][j] < d[i][j]) d[i][j] = d[i][k] + d[k][j];
while (q--) {
int u, v;
cin >> u >> v;
cout << (d[u][v] >= INF ? -1 : d[u][v]) << "\n";
}
return 0;
}
▶ Open this solution in the compiler, then press Visualize to watch it run step by step