一、题目链接
二、题目分析
(一)算法标签
负环判定 spfa
(二)解题思路
三、AC代码
解法一:
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
const int N = 2010, M = 10010;
int n, m;
int x, y, z;
// 稀疏图用邻接表存储
int h[N], w[M], e[M], ne[M], idx;
int dist[N], cnt[N];
bool st[N]; // 是否入队列
void add(int x, int y, int z) {
e[idx] = y, w[idx] = z, ne[idx] = h[x], h[x] = idx ++;
}
bool spfa() {
// 不需要初始化了, 因为不是求距离的绝对值, 求是否有负环
// memset(dist, 0x3f, sizeof dist);
// dist[1] = 0;
queue<int> q;
// 题目求整个图中是否存在负环, 而不是说从1开始的负环, 可能从1号点到不了负环
// q.push(1);
// st[1] = true;
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 != -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() {
memset(h, -1, sizeof h);
cin >> n >> m;
while (m --) {
cin >> x >> y >> z;
add(x, y, z);
}
if (spfa()) puts("Yes");
else puts("No");
return 0;
}