标签:
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条双向边,W条单向虫洞,走过每条边花费的时间是正的,走虫洞会让时间倒流,每条边和虫洞的花费已知,问小明从起点开始转一圈再回到起点的时间,能不能是在出发之前。
题目解析:用bellman_ford算法,判断是不是存在负环。
代码如下:
1 # include<iostream> 2 # include<cstdio> 3 # include<cstring> 4 # include<algorithm> 5 using namespace std; 6 const int INF=1<<29; 7 struct edge 8 { 9 int fr,to,w,nxt; 10 }; 11 edge e[8000]; 12 int head[550],n,cnt,dis[550]; 13 void add(int u,int v,int w) 14 { 15 e[cnt].fr=u; 16 e[cnt].to=v; 17 e[cnt].w=w; 18 //e[cnt].nxt=head[u]; 19 //head[u]=cnt++; 20 ++cnt; 21 } 22 bool bellman_ford() 23 { 24 int i,j; 25 fill(dis,dis+n+1,INF); 26 dis[1]=0; 27 for(i=0;i<n;++i){ 28 for(j=0;j<cnt;++j){ 29 if(dis[e[j].fr]!=INF&&dis[e[j].to]>dis[e[j].fr]+e[j].w){ 30 dis[e[j].to]=dis[e[j].fr]+e[j].w; 31 if(i==n-1) 32 return true; 33 } 34 } 35 } 36 return false; 37 } 38 int main() 39 { 40 int T,s,t; 41 scanf("%d",&T); 42 int a,b,c; 43 while(T--) 44 { 45 cnt=0; 46 memset(head,-1,sizeof(head)); 47 scanf("%d%d%d",&n,&s,&t); 48 while(s--) 49 { 50 scanf("%d%d%d",&a,&b,&c); 51 add(a,b,c); 52 add(b,a,c); 53 } 54 while(t--) 55 { 56 scanf("%d%d%d",&a,&b,&c); 57 add(a,b,-c); 58 } 59 if(bellman_ford()) 60 printf("YES\n"); 61 else 62 printf("NO\n"); 63 } 64 return 0; 65 }
标签:
原文地址:http://www.cnblogs.com/20143605--pcx/p/4681810.html