Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 31422 | Accepted: 11429 |
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
这题就是判存不存在负圈,可以用bellman-ford或者spfa,这里为了练习spfa。注意一下,在题目没有说明图连通的情况下,必须对每个点进行spfa判负圈,实际上可以优化,即每做一次spfa,dist!=inf,这些点不用继续spfa了。可以证明,如果这些点包含负圈,那么在这次spfa中就可以判出存在负圈,既然还要往下做,显然不存在负圈。
代码:
#include<cstdio> #include<iostream> #include<cstring> #define Maxe 6000 #define Maxv 510 using namespace std; struct line{ int to,w; line(){} line(int t,int ww):to(t),w(ww){} }edge[Maxe]; int head[Maxv],nxt[Maxe],f[Maxv]; int q[Maxv],dist[Maxv],vis[Maxv],cnt[Maxv]; const int inf=1<<30; bool spfa(int u,int n){ memset(vis,0,sizeof vis); memset(cnt,0,sizeof cnt); for(int i=1;i<=n;i++) dist[i]=inf; dist[u]=0,cnt[u]++; int s=0,e; q[e=1]=u; bool flag=true; while(s!=e&&flag){ int v=q[s=(s+1)%Maxv]; vis[v]=0; for(int i=head[v];i!=-1;i=nxt[i]){ int r=edge[i].to,w=edge[i].w; if(dist[v]+w<dist[r]){ dist[r]=dist[v]+w; if(++cnt[r]>=n) {flag=false;break;} if(!vis[r]) {q[e=(e+1)%Maxv]=r;vis[r]=1;} } } } if(!flag) return false; for(int i=1;i<=n;i++) if(dist[i]!=inf) f[i]=true; return true; } int main() { int t,n,m,s,fr,to,w; scanf("%d",&t); while(t--){ memset(head,-1,sizeof head); scanf("%d%d%d",&n,&m,&s); for(int i=0;i<m+s;i++){ scanf("%d%d%d",&fr,&to,&w); w=i>=m?-w:w; edge[i+m]=line(to,w),nxt[i+m]=head[fr],head[fr]=i+m; if(i<m) edge[i]=line(fr,w),nxt[i]=head[to],head[to]=i; } memset(f,0,sizeof f); int k=1; for(;k<=n;k++) if(!f[k]){ if(!spfa(k,n)) break; } if(k<=n) puts("YES"); else puts("NO"); } return 0; }