标签:
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
1 #include<cstdio> 2 #define MAXM 2710 3 #define MAXV 505 4 #define inf 1<<29 5 6 struct node{ 7 int x,y,t; 8 }edge[MAXM]; 9 10 int n,m,w;//n区域个数 m条路 w个虫洞 11 12 int bellman_ford() 13 { 14 int i,j,d[MAXV],flag=1,cnt=1; 15 for(i=1;i<=n;i++) 16 d[i]=inf;//出发点到i的距离全部初始化为无穷大 17 while(flag) 18 { 19 flag=0;//是为了把所有路走一遍 20 if(cnt++>n) 21 return 1; 22 //i是路的标号 23 for(i=1;i<=m;i++)//普通道路(非虫洞)找最短路 24 { 25 //分别找到edge[i].x和edge[i].y的最短距离 26 if(d[edge[i].x]+edge[i].t < d[edge[i].y]) 27 {d[edge[i].y] = d[edge[i].x]+edge[i].t; flag=1;} 28 if(d[edge[i].y]+edge[i].t < d[edge[i].x]) 29 {d[edge[i].x] = d[edge[i].y]+edge[i].t; flag=1;} 30 } 31 for(;i<=m+w;i++)//虫洞找最短路 32 if(d[edge[i].y] > d[edge[i].x]-edge[i].t) 33 {d[edge[i].y] = d[edge[i].x]-edge[i].t; flag=1;} 34 } 35 return 0; 36 } 37 38 int main() 39 { 40 int t,i; 41 scanf("%d",&t); 42 while(t--) 43 { 44 scanf("%d%d%d",&n,&m,&w); 45 for(i=1;i<=m+w;i++) 46 scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].t); 47 if(bellman_ford()) 48 printf("YES\n"); 49 else 50 printf("NO\n"); 51 } 52 return 0; 53 }
poj Wormholes 【最短路径】【bellman_ford】
标签:
原文地址:http://www.cnblogs.com/123tang/p/5951115.html