Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 40566 | Accepted: 14864 |
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
Source
题意:
给出n 顶点,以及某些点之间移动需要消耗的时间,另有一些单向的边,权值为负,表示可以时间可以倒流多少,给出整个图的信息,问这个人能否在任意起点出发,最终回到起点时的时间在出发的时间之前
题解:“
不难发现,如果图中出现了边的总权值为负的环,那么肯定可以满足题意(无限在环上跑,时间不是问题),也就是需要进行是否有负环的判断,
用spfa 进行最短路操作的时候,可以顺带发现负环...
/* http://blog.csdn.net/liuke19950717 */ #include<cstdio> #include<cstring> #include<queue> #include<algorithm> using namespace std; const int inf=0x3f3f3f3f; const int maxn=2505; int edgenum,head[maxn]; struct node { int from,to,val; int next; }edge[maxn*maxn]; void init() { edgenum=0; memset(head,-1,sizeof(head)); } void add(int a,int b,int c) { node tp={a,b,c,head[a]}; edge[edgenum]=tp; head[a]=edgenum++; } void slove(int n,int st) { int dist[maxn],vis[maxn]={0},num[maxn]={0}; memset(dist,inf,sizeof(dist)); vis[st]=1;num[st]=1;dist[st]=0; queue<int> q; q.push(st); while(!q.empty()) { int u=q.front();q.pop(); vis[u]=0; for(int i=head[u];i!=-1;i=edge[i].next) { int v=edge[i].to; if(dist[v]>dist[u]+edge[i].val) { dist[v]=dist[u]+edge[i].val; if(!vis[v]) { vis[v]=1;++num[v]; q.push(v); if(num[v]>n)//负环 { printf("YES\n"); return; } } } } } printf("NO\n"); } int main() { int t; scanf("%d",&t); while(t--) { int n,m,w; scanf("%d%d%d",&n,&m,&w); init(); for(int i=0;i<m+w;++i) { int a,b,c; scanf("%d%d%d",&a,&b,&c); i<m?add(a,b,c),add(b,a,c):add(a,b,-c); } slove(n,1); } return 0; }
ps:
本来该是学最短路的时候做这样的题目,到现在才做,真是够了.....图论也忘记的差不多了....