P2294题解
czhusi
·
·
个人记录
思路
显然要满足 a_i + w = a_j,这个条件,分别满足
-
a_i + w \leq a_j
-
a_i + w \geq a_j
即可。
然后稍作变换就变成了:
-
a_i + w \leq a_j
-
a_j - w \leq a_i
最后显然,如果有正环则为 $false$, 否则为 $true$。~~显然关于 `SPFA` 它死了,所以我们要用 `BELLMAN`~~
记住不保证联通,要超级源点哦!
## 代码
```cpp
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define int ll
const int N = 2e5 + 10, INF = LLONG_MAX / 2;
int n, m, dis[N];
struct Node {
int x, y, w;
};
vector<Node> v;
int bellman(int n) {
fill(dis, dis + n + 3, INF);
dis[n + 1] = 0;
int f = 0;
for (int i = 1; i <= n + 2; i++) {
f = 0;
for (auto j : v) {
if (dis[j.y] > dis[j.x] + j.w) {
dis[j.y] = dis[j.x] + j.w;
f = 1;
}
}
}
for (auto j : v) {
if (dis[j.y] > dis[j.x] + j.w) {
return 1;
}
}
return f;
}
signed main() {
ios::sync_with_stdio(0), cin.tie(0);
int T;
cin >> T;
while(T--) {
cin >> n >> m;
v.clear();
for(int i = 1, x, y, w; i <= m; i++) {
cin >> x >> y >> w;
v.push_back({x - 1, y, w});
v.push_back({y, x - 1, -w});
}
for(int i = 0; i <= n; i++) {
v.push_back({n + 1, i, 0});
}
if(!bellman(n)) {
cout << "true";
} else {
cout << "false";
}
cout << '\n';
}
return 0;
}
```