这道题要求的是给定一个图,判断是否存在一个负环。
很容易就想到Bellman-Ford算法,但是此题所提供的图可能是不连通的,因此题中的图可能会分成几个子图,而Bellman-Ford只能够判断源点所在子图是否存在负环,其他子图由于未连通而无法判断。因此,简单的使用Bellman-Ford是不行的。
那么怎么解决这个问题呢?可以想到,我们能不能在每个子图中都设一个源点,这样每个子图就可以判断是否存在负环了。怎么实现?可以用并查集,把每个结点分成几个集合,将每个结合的根结点设为源点,这样就可以解决了。
代码如下:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
#include<cmath>
#define inf 100000005
using namespace std;
const int maxn=5e2+5;
int dis[maxn],fa[maxn],inq[maxn],cnt[maxn]; //inq[]表示某个结点是否已经入队,cnt[]表示某个节点的入队次数。
struct edge
{
int v,T;
};
vector<edge> G[maxn];
int find(int root)
{
int son, tmp;
son = root;
while(root != fa[root])
root = fa[root];
while(son != root) //路径压缩,防止出现链式结构(套网上大佬的模板的)
{
tmp = fa[son];
fa[son] = root;
son = tmp;
}
return root;
}
void unit(int x,int y)
{
int fx=find(x),fy=find(y);
if(fx!=fy)
fa[fx]=fy;
}
bool Bellman_Ford(int n) //原本我是用一般形式的Bellman来做的,结果超时了,改成了队列优化后,时间125MS就AC,可见这种方法在时间上是有很大优势的
{
queue<int> Q;
for(int i=1;i<=n;i++)
{
inq[i]=0;
cnt[i]=0;
if(fa[i]==i) //fa[i]==i,说明i是所在集合的根结点,将其设为源点
{
dis[i]=0; //dis[i]=0就表示是源点l
inq[i]=1;
Q.push(i);
}
else dis[i]=inf;
}
while(!Q.empty())
{
int u=Q.front(); Q.pop();
inq[u]=0;
for(int i=0;i<G[u].size();++i)
{
edge e=G[u][i];
if(dis[u]<inf&&dis[e.v]>dis[u]+e.T) //负环<,正环>,零环=
{
dis[e.v]=dis[u]+e.T;
if(!inq[e.v])
{
Q.push(e.v); inq[e.v]=1;
if(++cnt[e.v]>n) return true; //一个有n个结点的图,最短路径最多只能经过n-1个节点,因此如果某个节点已经更新(入队)超过n次了,就说明是存在负环了
}
}
}
}
return false;
}
int main()
{
int F,N,M,W;
scanf("%d",&F);
while(F--)
{
scanf("%d%d%d",&N,&M,&W);
for(int i=1;i<=N;i++) fa[i]=i;
for(int i=1;i<=M;i++)
{
int a; edge e;
scanf("%d%d%d",&a,&e.v,&e.T);
unit(a,e.v);
G[a].push_back(e);
swap(a,e.v);
G[a].push_back(e);
}
for(int i=1;i<=W;i++)
{
int a; edge e;
scanf("%d%d%d",&a,&e.v,&e.T);
unit(a,e.v);
e.T=-e.T;
G[a].push_back(e);
}
if(Bellman_Ford(N))
printf("YES\n");
else printf("NO\n");
for(int i=1;i<=N;i++)
G[i].clear();
}
return 0;
}