![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d1cc05d915b83a577edc65e36ae6fd42.png)
题解
- 原理:我们可以用一个cnt[t] 来记录点1 - t 经过的点数,那么每次拿t来更新其他点 j 的最小距离时,cnt[j] =cnt[t]+1 (1—>t—>j) ,那么当cnt[j]>=n,表示1-j之间(包括自己)最少有n+1个点,肯定是不合法的
- 为什么会出现cnt[j]>=n这种情况呢,就是因为图中存在负环,每次经过负环dist都会变小,所以会一直更新,那么cnt[j]就是一直变大超出n
代码
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, m;
int h[N], e[N], w[N], ne[N], idx;
int dist[N], cnt[N];
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 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() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
memset(h, -1, sizeof h);
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
if(spfa()) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
return 0;
}