跳到正文

个人记录

P2294题解

czhusi约 3 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 3 分钟

版本

  1. v1当前

思路

显然要满足 ai+w=aja_i + w = a_j,这个条件,分别满足

  • ai+w≤aja_i + w \leq a_j
  • ai+w≥aja_i + w \geq a_j

即可。

然后稍作变换就变成了:

  • ai+w≤aja_i + w \leq a_j
  • aj−w≤aia_j - w \leq a_i

soso 连边是我们可以连两条边,一个正向边值为正;一个反向边权为负。

最后显然,如果有正环则为 falsefalse, 否则为 truetrue。显然关于 SPFA 它死了,所以我们要用 BELLMAN

记住不保证联通,要超级源点哦!

代码

C++
#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;
}
原文