John's farm contains n plots of land, m links are connected to two plots of land, k are wormhole holes, and the wormhole holes are one-way routes that not only send you to your destination, and the time will go backwards. Our task is to know if we will return again after starting from a certain place and see ourselves before leaving. Idea: the edge connected by the wormhole is a negative weight. If there is a negative ring on the way, he can keep following this change, and the time must be a negative value.
# Include <string. h> # include <stdio. h> const int N = 510; const int inf = 0x3fffffff; int start, num, n, dist [N]; struct edge {int st, ed, w ;} e [6000]; void addedge (int x, int y, int w) {e [num]. st = x; e [num]. ed = y; e [num ++]. w = w;} int Bellman_Ford () {int flag = 0, I, u, v, j; for (I = 1; I <= n; I ++) dist [I] = inf; dist [start] = 0; for (I = 1; I <n; I ++) // n-1 relaxation {for (j = 0; j <num; j ++) {u = e [j]. st; v = e [j]. ed; if (dist [v]> dist [u] + e [j]. w) {dist [v] = dist [u] + e [j]. w; flag = 1 ;}}if (flag = 0) break;} for (I = 0; I <num; I ++) if (dist [e [I]. ed]> dist [e [I]. st] + e [I]. w) // return 1; return 0;} int main () {int m, I, x, y, k, t, Case; scanf ("% d", & Case); while (Case --) {scanf ("% d", & n, & m, & k ); num = 0; for (I = 1; I <= m; I ++) {scanf ("% d", & x, & y, & t); addedge (x, y, t); addedge (y, x, t) ;}for (I = 0; I <k; I ++) {scanf ("% d", & x, & y, & t); addedge (x, y,-t);} start = 0; if (Bellman_Ford () printf ("YES \ n"); else printf ("NO \ n");} return 0 ;}