bzoj1715[Usaco2006 Dec]Wormholes 虫洞*

bzoj1715[Usaco2006 Dec]Wormholes 虫洞

题意:

判一个图是否有负环。点数≤500,边数≤3000。(我看不懂原题,后来看了题解,就直接这样说了)

题解:

SPFA中如果一个点被更新了n次以上,那么这个图中存在负环。

代码:

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <algorithm>
 4 #include <queue>
 5 #define inc(i,j,k) for(int i=j;i<=k;i++)
 6 #define maxn 510
 7 #define INF 0x3fffffff
 8 using namespace std;
 9 
10 inline int read(){
11     char ch=getchar(); int f=1,x=0;
12     while(ch<'0'||ch>'9'){if(ch=='-')f=-1; ch=getchar();}
13     while(ch>='0'&&ch<='9')x=x*10+ch-'0',ch=getchar();
14     return f*x;
15 }
16 struct e{int t,w,n;}es[maxn*15]; int g[maxn],ess;
17 void pe(int f,int t,int w){es[++ess]=(e){t,w,g[f]}; g[f]=ess;}
18 int f,n,m,w,d[maxn],cnt[maxn]; bool inq[maxn]; queue<int>q;
19 bool spfa(){
20     while(!q.empty())q.pop(); inc(i,1,n)d[i]=INF,cnt[i]=inq[i]=0; d[1]=0; inq[1]=1; q.push(1);
21     while(!q.empty()){
22         int x=q.front(); q.pop(); inq[x]=0;
23         for(int i=g[x];i;i=es[i].n)if(d[es[i].t]>d[x]+es[i].w){
24             d[es[i].t]=d[x]+es[i].w; cnt[es[i].t]++; if(cnt[es[i].t]>n)return 1;
25             if(!inq[es[i].t])q.push(es[i].t),inq[es[i].t]=1;
26         }
27     }
28     return 0;
29 }
30 int main(){
31     f=read();
32     while(f--){
33         n=read(); m=read(); w=read(); memset(g,0,sizeof(g)); ess=0;
34         inc(i,1,m){int x=read(),y=read(),z=read(); pe(x,y,z); pe(y,x,z);}
35         inc(i,1,w){int x=read(),y=read(),z=read(); pe(x,y,-z);}
36         if(spfa())puts("YES");else puts("NO");
37     }
38     return 0;
39 }

20160912

原文地址:https://www.cnblogs.com/YuanZiming/p/5876564.html