Last active
November 27, 2019 17:41
-
-
Save shiponcs/28c4fee2048ec750d0e0fa15723f9b32 to your computer and use it in GitHub Desktop.
Bellman ford algorithm(negative cycle finding)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
using namespace std; | |
const int inf = 1e8; | |
int main() | |
{ | |
int tcc; | |
cin >> tcc; | |
while(tcc--) { | |
int n, m, u, v, wt; | |
cin >> n >> m; | |
vector< pair< int, int > > edges; | |
int cost[n + 1][n + 1]; | |
for(int i = 0; i < m; i++) { | |
cin >> u >> v >> wt; | |
edges.push_back( {u, v} ); // u -> v | |
cost[u][v] = wt; | |
} | |
int dist[n + 1]; | |
for(int i = 0; i < n + 1; i++) dist[i] = inf; | |
dist[0] = 0; | |
for(int i = 0; i < n - 1; i++) { | |
for(pair< int, int > x: edges){ | |
int ut = x.first, vt = x.second; | |
if( dist[vt] > dist[ut] + cost[ut][vt] ){ | |
dist[vt] = dist[ut] + cost[ut][vt]; | |
} | |
} | |
} | |
bool flag = false; | |
for(pair< int, int > x: edges) { | |
int ut = x.first, vt = x.second; | |
if( dist[vt] > dist[ut] + cost[ut][vt] ){ | |
cout << "possible\n"; | |
flag = true; | |
break; | |
} | |
} | |
if( !flag ){ | |
cout << "not possible\n"; | |
} | |
edges.clear(); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment