AcWing 852. spfa判断负环
原题链接
简单
作者:
芝居気
,
2021-12-05 19:24:42
,
所有人可见
,
阅读 129
#include<iostream>
#include<cstring>
#include<algorithm>
#include<queue>
using namespace std;
#define db(x) cout<<#x<<" = "<<x<<". ";
int n, m;
const int N = 100005;
int e[N], ne[N], h[N], idx;
int w[N];
bool st[N];
int dis[N];
int cnt[N];
bool ans;
void add(int a, int b, int c)
{
w[idx] = c;
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
void spfa()
{
memset(dis, 0x3f, sizeof(dis));
dis[1] = 0;
queue<int> q;
for (int i = 1; i <= n; i++)
{
q.push(i); st[i] = 1;
}
while (q.size())
{
int temp = q.front();
//db(temp) cout<<endl;
q.pop();
st[temp] = 0;
for (int i = h[temp]; ~i; i = ne[i]) //经过了松弛操作的点可能影响其他点,需要入列
{ //没有松弛的点无法影响后继,更无法影响n点,所以不需要再更新了。
int j = e[i];
if (dis[j] > dis[temp] + w[i]) //比起广搜增加判定入列条件从全入变成了距离缩短的且没在队列的入
{
cnt[j]=cnt[temp]+1;
if(cnt[j]>=n) {ans=1;return;}
dis[j] = dis[temp] + w[i];
if (!st[j])
{
q.push(j);
st[j] = 1;
}
}
}
}
}
int main()
{
memset(h, -1, sizeof h);
cin >> n >> m;
for (int i = 0; i < m; i++)
{
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
spfa();
if(ans==1) cout<<"Yes";
else cout<<"No";
}