题目描述
抽屉原理
dist[x],表示当前 1 到 x 的最短距离
cnt[x],表示 1 到 x 当前这个最短路边的数量
如果过程中,cnt[x] >= x,表示从 1 到 x 至少经过了 n 条边,那么至少有 n + 1 个点
根据抽屉原理,一定有两个点的值是相同的,表面路径上存在一个环,并且是一个负环
样例
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 150010;
int n, m;
int h[N], e[N], ne[N],idx;
int w[N];
int dist[N];
bool st[N];
int cnt[N];
void add(int a, int b, int c)
{
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx ++;
}
bool spfa()
{
queue<int> q;
// q.push(1);
// st[1] = true;
// 最开始的时候需要把所有点放在队列里边,因为 环 不一定 经过1
for(int i = 1; i <= n; i++)
{
st[i] = true;
q.push(i);
}
while(q.size())
{
int t = q.front();
q.pop();
st[t] = false;
for(int i = h[t]; i != -1; i = ne[i])
{
int j = e[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;
}