Skip to content

Instantly share code, notes, and snippets.

@NamPE286
Created April 19, 2023 00:59
Show Gist options
  • Save NamPE286/3367af6e5a5d903cf01bd311be4e0fea to your computer and use it in GitHub Desktop.
Save NamPE286/3367af6e5a5d903cf01bd311be4e0fea to your computer and use it in GitHub Desktop.
Floyd Warshall's algorithm implementation in C++ (used to calculate all vertex pair distance) (better than dijkstra when E > V^3)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int main(){
ios::sync_with_stdio(0);
cout.tie(0);
cin.tie(0);
ll n, m, q;
cin >> n >> m >> q;
vector<vector<ll>> mat(n + 1, vector<ll>(n + 1, 1e16));
for(ll i = 0; i < m; i++){
ll a, b, w;
cin >> a >> b >> w;
mat[a][b] = mat[b][a] = min(mat[a][b], w);
}
for(ll k = 1; k <= n; k++){
for(ll i = 1; i <= n; i++){
for(ll j = i + 1; j <= n; j++){
mat[i][j] = mat[j][i] = min(mat[i][j], mat[i][k] + mat[k][j]);
}
}
}
while (q--){
ll a, b;
cin >> a >> b;
if(a == b) mat[a][b] = 0;
if(mat[a][b] == 1e16) cout << -1 << '\n';
else cout << mat[a][b] << '\n';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment