Acwing 852. spfa判断负环
题目描述
给定一个 n 个点 m条边的有向图,图中可能存在重边和自环, 边权可能为负数。
请你判断图中是否存在负权回路。
输入格式
第一行包含整数 n 和 m。
接下来 m
行每行包含三个整数 x,y,z,表示存在一条从点 x 到点 y 的有向边,边长为 z
输出格式
如果图中存在负权回路,则输出 Yes,否则输出 No。
数据范围
1≤n≤2000,
1≤m≤10000,
图中涉及边长绝对值均不超过 10000。
思路
我们用cnt来记录到达这个点最短路径经历过的边的数目,如果存在负环,那么那个环上的点就会不断的遍历。经过的数量就会一直变大。
利用这个特性每次更新判断是否经过n个点。
代码
#include<iostream>
#include<queue>
#include<cstring>
using namespace std ;
const int N = 100010;
int idx,e[N],ne[N],h[N],w[N];
int dist[N],cnt[N];
int n, m;
bool st[N];
void add(int a,int b ,int c)
{
e[idx] = b,w[idx] = c, ne[idx] = h[a],h[a] = idx ++ ;
}
bool spfa()
{
queue<int>q;
for(int i = 1 ; i <= n ; ++ i)
{
q.push(i);
st[i] = true ;
}
while(q.size())
{
auto t = q.front();
q.pop();
st[t] = false;
for(int i = h[t] ; i != -1 ; i = ne[i])
{
int d= e[i];
if(dist[d] > dist[t] + w[i])
{
cnt[d] = cnt[t] +1;
dist[d] = dist[t] +w[i];
if(cnt[d] >= n)
return true;
if(!st[d])
{
q.push(d);
st[d] = true ;
}
}
}
}
return false;
}
int main()
{
cin>>n>>m;
memset(h,-1,sizeof h);
while(m--)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
}
if(spfa()) puts("Yes");
else puts("No");
return 0;
}
}
if(spfa()) puts("Yes");
else puts("No");
return 0;
}