(简单) POJ 3259 Wormholes,SPFA判断负环。

时间:2023-03-10 00:33:13
(简单) POJ 3259 Wormholes,SPFA判断负环。

  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.

  就是求是否存在负环,这样的话一定能够时间倒退。。。

代码如下:

#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue> using namespace std; const int INF=10e8;
const int MaxN=; struct Edge
{
int v,cost; Edge(int _v,int _cost):v(_v),cost(_cost) {}
}; vector <Edge> E[MaxN];
bool vis[MaxN];
int couNode[MaxN]; bool SPFA(int lowcost[],int n,int start)
{
queue <int> que;
int u,v,c;
int len; for(int i=;i<=n;++i)
{
lowcost[i]=INF;
vis[i]=;
couNode[i]=;
}
vis[start]=;
couNode[start]=;
lowcost[start]=; que.push(start); while(!que.empty())
{
u=que.front();
que.pop(); vis[u]=;
len=E[u].size(); for(int i=;i<len;++i)
{
v=E[u][i].v;
c=E[u][i].cost; if(lowcost[u]+c<lowcost[v])
{
lowcost[v]=lowcost[u]+c; if(!vis[v])
{
vis[v]=;
++couNode[v];
que.push(v); if(couNode[v]>=n)
return ;
}
}
}
} return ;
} inline void addEdge(int u,int v,int c)
{
E[u].push_back(Edge(v,c));
} int ans[MaxN]; int main()
{
int T;
int N,M,W;
int a,b,c; scanf("%d",&T); while(T--)
{
scanf("%d %d %d",&N,&M,&W); for(int i=;i<=N;++i)
E[i].clear(); for(int i=;i<=M;++i)
{
scanf("%d %d %d",&a,&b,&c); addEdge(a,b,c);
addEdge(b,a,c);
} for(int i=;i<=W;++i)
{
scanf("%d %d %d",&a,&b,&c); addEdge(a,b,-c);
} if(SPFA(ans,N,))
printf("NO\n");
else
printf("YES\n");
} return ;
}