POJ-3259-Wormholes
Http://poj.org/problem? Id = 3259
Bellman_ford determines whether a negative ring exists
# Include <iostream> # include <cstdio> # include <cstring> # include <cstdlib> using namespace STD; # define Max 0x7fffffffstruct edge {int X, Y, V ;} edge [6000]; int m, n, W; int dis [600]; int bellman_ford (int K) {int I, j, flag; for (I = 1; I <= N; I ++) dis [I] = max; DIS [1] = 0; flag = 0; for (I = 1; I <N; I ++) // relaxation {flag = 0; For (j = 0; j <K; j ++) if (DIS [edge [J]. x]! = Max & dis [edge [J]. y]> dis [edge [J]. x] + edge [J]. v) {dis [edge [J]. y] = dis [edge [J]. x] + edge [J]. v; flag = 1;} If (! Flag) // No change after one update. You do not need to update break again next time;} for (I = 0; I <K; I ++) // adding this edge can shorten the path strength, indicating that there is a negative ring if (DIS [edge [I]. y]> dis [edge [I]. x] + edge [I]. v) return 1; return 0;} int main () {int t; int A, B, C, K; scanf ("% d", & T ); while (t --) {scanf ("% d", & N, & M, & W); k = 0; while (M --) {scanf ("% d", & A, & B, & C); edge [K]. X = A; edge [K]. y = B; edge [K]. V = C; k ++; edge [K]. X = B; edge [K]. y = A; edge [K]. V = C; k ++;} while (w --) {scanf ("% d", & A, & B, & C ); edge [K]. X = A; edge [K]. y = B; edge [K]. V =-C; k ++;} If (bellman_ford (k) printf ("Yes \ n"); else printf ("NO \ n ");} return 0 ;}