poj Wormholes 最短路径bellman_ford
Posted 唐唐123
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了poj Wormholes 最短路径bellman_ford相关的知识,希望对你有一定的参考价值。
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
Line 1 of each farm: Three space-separated integers respectively: N, M, and W
Lines 2..M+1 of each farm: Three space-separated numbers (S, E, T) that describe, respectively: a bidirectional path between S and E that requires T seconds to traverse. Two fields might be connected by more than one path.
Lines M+2..M+W+1 of each farm: Three space-separated numbers (S, E, T) that describe, respectively: A one way path from S to E that also moves the traveler back T seconds.
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
For farm 2, FJ could travel back in time by the cycle 1->2->3->1, arriving back at his starting location 1 second before he leaves. He could start from anywhere on the cycle to accomplish this.
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的主要内容,如果未能解决你的问题,请参考以下文章
图的最短路径-----------SPFA算法详解(TjuOj2831_Wormholes)