题解:P17481 平衡路线

· · 题解

P17481 平衡路线 题解

哦不不不不这无疑是所有 2026 S组 初赛考生噩梦前的最后一丝慰藉

思路

言归正传,题面已经讲得很清楚了,这里不做解释

可以发现一个性质:可以在一条边上来回横跳来改变权值,对 + 边贡献 +2,对 - 边贡献 -2 ,通过多次加加减减使答案接近 0 ,但不会改变答案的奇偶性。

所以如果在从 s 出发能到达的连通分量中,边的种类既有 + 又有 - ,我们只需关注到达 t 的路径的奇偶性就行,若经过的边的数量为偶数,则答案一定为 0 ,否则为 1。

对于两种边都有的情况还要分两类:

对于只有一种边的情况:

可以对图进行二分图染色来判断是否存在奇环和路径的奇偶性。

代码(其实就是初赛的题面)

#include <iostream>
constexpr int N = 200005;
constexpr int M = 400005;
int n, m, s, t;
int h[N], e[M << 1], ne[M << 1], w[M << 1], idx;
int q[N], d[N], c[N];
void add(int a, int b, int z) {
    e[idx] = b;
    w[idx] = z;
    ne[idx] = h[a];
    h[a] = idx++;
}
int main() {
    std::cin >> n >> m >> s >> t;
    for (int i = 1; i <= n; i++)
        h[i] = d[i] = c[i] = -1;
    for (int i = 0; i < m; i++) {
        int a, b;
        char op[2];
        std::cin >> a >> b >> op;
        int z = op[0] == '+' ? 1 : -1;
        add(a, b, z);
        add(b, a, z);
    }
    int hh = 0, tt = 0;
    int p = 0, ng = 0, ok = 1;
    q[tt++] = s;
    d[s] = c[s] = 0;
    while (hh < tt) {
        int x = q[hh++];
        for (int i = h[x]; i != -1; i = ne[i]) {
            int y = e[i];
            if (w[i] > 0) p = 1;
            if (w[i] < 0) ng = 1;
            if (d[y] == -1) {
                d[y] = d[x] + 1;//计算只有一种边时的贡献
                c[y] = c[x] ^ 1;//二分图染色
                q[tt++] = y;
            } else if (c[y] == c[x])
                ok = 0;
        }
    }
    if (d[t] == -1) {//若无法到达
        std::cout << -1;
        return 0;
    }
    if (!p || !ng) {//若只有一种边
        std::cout << d[t];
        return 0;
    }
  //若存在奇环或起点到终点所经过的边的数量为偶数
    if (!ok || c[s] == c[t]) std::cout << 0;
    else std::cout << 1;
    return 0;
}