The shortest path Bellman algorithm, simply use to determine whether there is a negative ring part, because as long as there is a negative circle, there must be a way to return to the starting point and time to restore (first test instructions understanding of the bad, note if the time to return to the beginning of a negative number, it is also possible, should be the default return start time, Because time cannot be negative. So, the essence is to judge whether there is a negative circle.
#include <cstdio> #include <iostream> #include <cstring>using namespace std;const int INF = 10000000; int f,n,m,w,d[2000],all_edge,a,b,c;struct edge{int from,to,cost; Edge (int from = 0,int to = 0,int Cost = 0): From, to, cost (cost) {}}s[6000];bool Bellman () {memset (d,0,sizeof (d)); for (int i=0;i<n;i++) {for (int j=0;j<all_edge;j++) {Edge E = Edge (S[j].from,s[j].to,s[j].cost); if (d[e.to] > D[e.from] + e.cost) {d[e.to] = D[e.from] + e.cost; if (i==n-1) return true; }}} return false;} int main () {scanf ("%d", &f); while (f--) {scanf ("%d%d%d", &n,&m,&w); All_edge = 0; for (int i=1;i<=m;i++) {scanf ("%d%d%d", &a,&b,&c); S[all_edge].from = A; S[all_edge].to = b; S[all_edge++].cost = C; S[all_edge].from = b; S[all_edge].to = A; S[all_edgE++].cost = C; } for (int i=1;i<=w;i++) {scanf ("%d%d%d", &a,&b,&c); S[all_edge].from = A; S[all_edge].to = b; S[all_edge++].cost =-C; } if (Bellman ()) printf ("yes\n"); else printf ("no\n"); } return 0;}
Wormholes. (POJ-3259)