852. spfa判断负环
作者:
闪回
,
2024-03-24 20:20:33
,
所有人可见
,
阅读 3
不需要初始化距离,将每个点都加入队列,记录一个cnt数组
#include<bits/stdc++.h>
using namespace std;
const int N = 2010;
const int M = 1e4+10;
int val[M],ne[M],h[N],w[M],idx;
int cnt[N],dist[N];
int n,m;
bool st[N];
void add(int a,int b,int weight)
{
val[idx] = b;
ne[idx] = h[a];
w[idx] = weight;
h[a] = idx++;
}
bool spfa()
{
queue<int> q;
for(int i = 1;i<=n;i++)
{
q.push(i);
st[i] = true;
}
while(q.size())
{
int t = q.front();
q.pop();
st[t] = false;
for(int i = h[t];~i;i = ne[i])
{
int j = val[i];
if(dist[j] > dist[t] + w[i])
{
dist[j] = dist[t] + w[i];
cnt[j] = cnt[t] + 1;
if(cnt[j] >= n)return true;
if(!st[j])
{
q.push(j);
st[j] = true;
}
}
}
}
return false;
}
int main()
{
cin>>n>>m;
memset(h,-1,sizeof h);
while (m -- )
{
int a,b,c;
cin>>a>>b>>c;
add(a,b,c);
}
if(spfa())puts("Yes");
else puts("No");
return 0;
}