Author: lllyouo
Date: 2025-04-06
tag: 差分约束
link: https://www.luogu.com.cn/problem/P1993问题描述
分析
略
参考代码
cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 5010, M = 2 * N;
int h[N], e[M], w[M], ne[M], idx;
int n, m;
int dist[N], vis[N], cnt[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);
vis[i] = 1;
}
while (!q.empty()) {
int k = q.front();
q.pop();
vis[k] = 0;
for (int i = h[k]; i != -1; i = ne[i]) {
int j = e[i];
if (dist[j] > dist[k] + w[i]) {
dist[j] = dist[k] + w[i];
cnt[j] = cnt[k] + 1;
if (cnt[j] >= n) return true;
if (!vis[j]) {
q.push(j);
vis[j] = 1;
}
}
}
}
return false;
}
int main() {
memset(h, -1, sizeof h);
cin >> n >> m;
for (int i = 1; i <= m; i++) {
int o, a, b, c; cin >> o;
if (o == 1) {
cin >> a >> b >> c;
add(a, b, -c);
} else if (o == 2) {
cin >> a >> b >> c;
add(b, a, c);
} else {
cin >> a >> b;
add(a, b, 0);
add(b, a, 0);
}
}
if (!spfa()) puts("Yes");
else puts("No");
return 0;
}