Initial commit: C++ courseware
This commit is contained in:
commit
4a4ee7c287
1789 files changed
+373489
No files matched your search
@@ -0,0 +1,44 @@
|
||||
// 教学版 Bellman-Ford 判环;输入格式与 P3385 一致。C++11。
|
||||
#include <iostream>
|
||||
#include <vector>
|
||||
using namespace std;
|
||||
using ll = long long;
|
||||
struct Edge { int u, v, w; };
|
||||
|
||||
bool hasNegativeCycle(int n, const vector<Edge>& edges, int s) {
|
||||
const ll INF = (1LL << 60);
|
||||
vector<ll> dis(n + 1, INF);
|
||||
dis[s] = 0;
|
||||
for (int k = 1; k <= n; ++k) {
|
||||
auto old = dis;
|
||||
bool changed = false;
|
||||
for (auto e : edges) {
|
||||
if (old[e.u] == INF) continue;
|
||||
ll nd = old[e.u] + e.w;
|
||||
if (nd < dis[e.v]) {
|
||||
dis[e.v] = nd;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if (!changed) return false;
|
||||
if (k == n) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
int main() {
|
||||
ios::sync_with_stdio(false);
|
||||
cin.tie(nullptr);
|
||||
int T;
|
||||
if (!(cin >> T)) return 0;
|
||||
while (T--) {
|
||||
int n, m; cin >> n >> m;
|
||||
vector<Edge> edges;
|
||||
for (int i = 0; i < m; ++i) {
|
||||
int u, v, w; cin >> u >> v >> w;
|
||||
edges.push_back({u, v, w});
|
||||
if (w >= 0) edges.push_back({v, u, w});
|
||||
}
|
||||
cout << (hasNegativeCycle(n, edges, 1) ? "YES" : "NO") << '\n';
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user