1 介绍
本专题用来记录使用spfa算法来求负环的题目。
2 训练
题目1:904虫洞
C++代码如下,
#include <cstring>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 510;
int n, m, w;
int dist[N], cnt[N];
bool st[N]; //st[i]表示结点i是否在队列中
vector<vector<PII>> g;
void spfa() {
queue<int> q;
for (int i = 1; i <= n; ++i) {
q.push(i);
st[i] = true;
}
while (!q.empty()) {
auto t = q.front();
q.pop();
st[t] = false;
for (auto [b, w] : g[t]) {
if (dist[b] > dist[t] + w) {
dist[b] = dist[t] + w;
cnt[b] = cnt[t] + 1;
if (!st[b]) {
q.push(b);
}
if (cnt[b] >= n) {
cout << "YES" << endl;
return;
}
}
}
}
cout << "NO" << endl;
return;
}
int main() {
int T;
cin >> T;
while (T--) {
cin >> n >> m >> w;
g.clear();
g.resize(n + 10);
for (int i = 0; i &l