1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
#include <iostream> #include <cstdio> #include <cstdlib> #define INF 1000000000 #define MX 2005 using namespace std; struct Edge{ int src; int dst; int weight; }; Edge e[MX]; bool bellman(int n,int m,int source) { bool negativecycle =false; int dist[n+5]; dist[source] = 0; for(int i=1;i<n;i++) dist[i]=INF; for(int i=1;i<=n-1;i++) { for(int j=0;j<m;j++) { if(dist[e[j].dst]>dist[e[j].src]+e[j].weight) dist[e[j].dst] = dist[e[j].src]+e[j].weight; } } for(int j=0;j<m;j++) { if(dist[e[j].dst]>dist[e[j].src]+e[j].weight) negativecycle = 1; } return negativecycle; } int main() { int n,m,t; int s,d,tym; cin>>t; while(t--) { cin>>n>>m; for(int i=0;i<m;i++) { cin>>s>>d>>tym; e[i].src = s; e[i].dst = d; e[i].weight = tym; } if(bellman(n,m,0)) cout<<"possible\n"; else cout<<"not possible\n"; } return 0; } |