【bzoj1715/Usaco2006 Dec】Wormholes 虫洞——SPFA判负环

Description

John在他的农场中闲逛时发现了许多虫洞。虫洞可以看作一条十分奇特的有向边,并可以使你返回到过去的一个时刻(相对你进入虫洞之前)。John的每个农场有M条小路(无向边)连接着N (从1..N标号)块地,并有W个虫洞。其中1<=N<=500,1<=M<=2500,1<=W<=200。 现在John想借助这些虫洞来回到过去(出发时刻之前),请你告诉他能办到吗。 John将向你提供F(1<=F<=5)个农场的地图。没有小路会耗费你超过10000秒的时间,当然也没有虫洞回帮你回到超过10000秒以前。

Input

* Line 1: 一个整数 F, 表示农场个数。

* Line 1 of each farm: 三个整数 N, M, W。

* Lines 2..M+1 of each farm: 三个数(S, E, T)。表示在标号为S的地与标号为E的地中间有一条用时T秒的小路。

* Lines M+2..M+W+1 of each farm: 三个数(S, E, T)。表示在标号为S的地与标号为E的地中间有一条可以使John到达T秒前的虫洞。

Output

* Lines 1..F: 如果John能在这个农场实现他的目标,输出"YES",否则输出"NO"。

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
 

题目就是问你联通图里是否存在负环,可以把每个点的dis都初始化为0,那么如果SPFA的dfs能走回原来点说明存在负环。
代码:
 1 #include<cstdio>
 2 #include<cstring>
 3 #include<algorithm>
 4 const int N=550;
 5 struct node{int ne,to,w;}e[5500];
 6 int n,first[N],tot=0,m,w,dis[N];
 7 bool flag,ok[N];
 8 int read(){
 9     int ans=0,f=1;char c=getchar();
10     while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
11     while(c>='0'&&c<='9'){ans=ans*10+c-48;c=getchar();}
12     return ans*f;
13 }
14 int ans=0;
15 void ins(int u,int v,int w){e[++tot]=(node){first[u],v,w};first[u]=tot;}
16 void dfs(int x){
17     ok[x]=1;
18     for(int i=first[x];i;i=e[i].ne){
19         int to=e[i].to;
20         if(dis[to]>dis[x]+e[i].w){
21             if(ok[to]){flag=1;return ;}
22             dis[to]=dis[x]+e[i].w;
23             dfs(to);
24         }
25     }
26     ok[x]=0;
27 }
28 void init(){
29     tot=0;flag=0;
30     for(int i=1;i<=n;i++)first[i]=ok[i]=dis[i]=0;
31 }
32 int main(){
33     int tt=read();
34     while(tt--){
35         n=read();m=read();w=read();init();
36         for(int i=1,a,b,c;i<=m;i++){
37             a=read();b=read();c=read();
38             ins(a,b,c);ins(b,a,c);
39         }
40         for(int i=1,a,b,c;i<=w;i++){
41             a=read();b=read();c=read();
42             ins(a,b,-c);
43         }
44         for(int i=1;i<=n;i++){dfs(i);if(flag)break;}
45         if(flag)printf("YES\n");
46         else printf("NO\n");
47     }
48     return 0;
49 }
50 
bzoj1715

 

posted @ 2017-10-14 10:48  Child-Single  阅读(318)  评论(0编辑  收藏  举报