Description
While exploring his many farms, Farmer John has discovered a number of amazing wormholes. A wormhole is very peculiar because it is a one-way path that delivers you to its destination at a time that is BEFORE you entered the wormhole! Each of FJ's farms comprises N (1 ≤ N ≤ 500) fields conveniently numbered 1..N, M (1 ≤ M ≤ 2500) paths, and W (1 ≤ W ≤ 200) wormholes.
As FJ is an avid time-traveling fan, he wants to do the following: start at some field, travel through some paths and wormholes, and return to the starting field a time before his initial departure. Perhaps he will be able to meet himself :) .
To help FJ find out whether this is possible or not, he will supply you with complete maps to F (1 ≤ F ≤ 5) of his farms. No paths will take longer than 10,000 seconds to travel and no wormhole can bring FJ back in time by more than 10,000 seconds.
Input
Output
Sample Input
2 3 3 1 1 2 2 1 3 4 2 3 1 3 1 3 3 2 1 1 2 3 2 3 4 3 1 8
Sample Output
NO YES
Hint
Source
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; const int MAX = 22222222; int F,N,M,W,cnt; int d[6000]; struct edge { int u; int v; int t; }edge[6000]; bool bellman_ford() { for(int i = 1; i <= N;i++) d[i] = MAX; d[1] = 0; bool flag; for(int i = 1; i <= N;i++){ flag = 1; for(int j = 0; j < cnt; j++){ if(d[edge[j].v]>d[edge[j].u]+edge[j].t){ flag = 0; d[edge[j].v] = d[edge[j].u]+edge[j].t; } } if(flag) return true; } return false; } int main() { int u,v,t; scanf("%d",&F); while(F--){ cnt = 0; scanf("%d%d%d",&N,&M,&W); for(int i = 1; i <= M;i++){ scanf("%d%d%d",&u,&v,&t); edge[cnt].u = u; edge[cnt].v = v; edge[cnt].t = t; cnt++; edge[cnt].u = v; edge[cnt].v = u; edge[cnt].t = t; cnt++; } for(int i = 1; i <= W;i++){ scanf("%d%d%d",&u,&v,&t); edge[cnt].u = u;edge[cnt].v = v;edge[cnt].t = -t; cnt++; } if(bellman_ford()) printf("NO\n"); else printf("YES\n"); } return 0; }