| Time Limit: 2000MS | Memory Limit: 65536K | |
| Total Submissions: 39078 | Accepted: 14369 |
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
题意:每个农场有N各区域,连接所有区域的是M个双向路径和W个单向时空隧道,从S->E若为路径则花费T秒,若为时空隧道则倒退T秒。问是否可以从某点出发,转一圈回来,回到出发时刻之前。
思路:因为时空隧道实现倒退,所以将其权值设为负值,利用ford判断是否存在负环。
#include"cstdio" #include"cstring" using namespace std; const int MAXN=10005; const int INF=0x3fffffff; struct Edge{ int from,to,cost; }es[MAXN]; int N,M,W; int E; int d[MAXN]; bool ford(int s) { for(int i=1;i<=N;i++) d[i]=INF; d[s]=0; int n=N; while(n--) { bool update=false; for(int i=0;i<E;i++) { Edge e=es[i]; if(d[e.from]!=INF&&d[e.to]>d[e.from]+e.cost) { d[e.to]=d[e.from]+e.cost; update=true; } } if(!update) break; } if(n==-1) return true; else return false; } int main() { int F; scanf("%d",&F); while(F--) { E=0; scanf("%d%d%d",&N,&M,&W); for(int i=0;i<M;i++) { int u,v,c; scanf("%d%d%d",&u,&v,&c); es[E].from=u,es[E].to=v,es[E++].cost=c; es[E].from=v,es[E].to=u,es[E++].cost=c; } for(int i=0;i<W;i++) { int u,v,c; scanf("%d%d%d",&u,&v,&c); es[E].from=u,es[E].to=v,es[E++].cost=-c;//倒退c秒 } if(ford(1)) printf("YES\n"); else printf("NO\n"); } return 0; }
原文:http://www.cnblogs.com/program-ccc/p/5149893.html