Typical Floyd-Walshall Algorithm.
#include <cmath> #include <cstdio> #include <vector> #include <string> #include <iostream> #include <algorithm> #include <queue> #include <unordered_map> #include <unordered_set> using namespace std; const long DIST_MAX = std::numeric_limits<long>::max(); int main() { const int INF = std::numeric_limits<int>::max(); // Get input int n, m; cin >> n >> m; vector<vector<int>> dist(n, vector<int>(n, INF)); int mm = m; while (mm--){ int x, y, r; cin >> x >> y >> r; dist[x - 1][y - 1] = r; } for (int i = 0; i < n; i++) dist[i][i] = 0; // Floyd-Walshall for (int v = 0; v < n; v ++) for (int f = 0; f < n; f++) for (int t = 0; t < n; t++) { if (f == t) continue; int fv = dist[f][v]; int vt = dist[v][t]; if (fv != INF && vt != INF) { if (dist[f][t] > (fv + vt)) dist[f][t] = fv + vt; } } // Queries int q; cin >> q; while (q--) { int a, b; cin >> a >> b; int ret = dist[a - 1][b - 1]; cout << (ret == INF ? -1 : ret) << endl; } return 0; }