题解:P14832 [THUPC 2026 初赛] Unpair Ampere

· · 题解

每个叶子有两种选择,直接网络流连边 S \to i \to i+n \to T。其中 i \to i+n 的边权为 +\infty,不可能被割掉。如果最终割掉 i+n \to T 就代表它最终选火力,如果割掉 S \to i 表示选太阳能。

考虑刻画一个非叶子点的贡献。如果同时有火力和太阳能的叶子能走到它,就会产生 a_i 的代价。考虑找出所有能到达 i 的叶子 j,并连边 j \to i 流量 +\infty,以及 i+n \to j 流量 +\infty。这样如果 S 能走到某个 j_0,并且某个 j_1 能走到 T,就必然存在 S \to j_0 \to \dots \to i \to i+n \to \dots \to j_1 \to T 这条路径。这条路径的实际意义就是 j_0 选火力,j_1 选太阳能,并且需要增加 a_i 的代价。最优解中割的边一定是 i \to i+n,把它的流量设成 a_i 即可。

另外为了防止一个叶子 i 的 S \to i 和 i \to T 两条边都被割掉,我们可以把它们加上一个较大值(不是 +\infty),最后答案减去即可。

:::success[Code]

#include <bits/stdc++.h>

using namespace std;

const int N = 20010, M = 2e6 + 10, K = 1000, INF = 1e9;

int n, m, d[N], a[N], S, T;
int h[N], e[M], ne[M], w[M], idx, cur[N];

void add(int a, int b, int c) {
    if (!c) return;
    e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx ++ ;
    e[idx] = a, ne[idx] = h[b], w[idx] = 0, h[b] = idx ++ ;
}

int dep[N];

bool bfs() {
    queue<int> q;
    memset(dep, -1, sizeof dep);
    dep[S] = 1;
    q.push(S);
    cur[S] = h[S];

    while (q.size()) {
        int u = q.front();
        q.pop();

        for (int i = h[u]; ~i; i = ne[i]) {
            int f = w[i], v = e[i];
            if (f && dep[v] == -1) {
                dep[v] = dep[u] + 1;
                cur[v] = h[v];
                if (v == T) return true; 
                q.push(v);
            }
        }
    }

    return dep[T] != -1;
}

int dfs(int u, int flow) {
    if (u == T) return flow;
    int res = 0;
    for (int &i = cur[u]; ~i && flow; i = ne[i]) {
        int f = w[i], v = e[i];
        if (f && dep[v] == dep[u] + 1) {
            int t = dfs(v, min(flow, f));
            if (t) {
                w[i] -= t;
                w[i ^ 1] += t;
                res += t;
                flow -= t;
            } else {
                dep[v] = -1;
            }
        }
    }
    return res;
}

int dinic() {
    int res = 0;
    while (bfs()) res += dfs(S, INF);
    return res;
}

signed main() {
    memset(h, -1, sizeof h);
    cin >> n >> m;

    S = 2 * n + 1, T = 2 * n + 2;
    for (int i = 1; i <= n; ++ i ) {
        cin >> d[i];
    }
    for (int i = 1; i <= n; ++ i ) {
        cin >> a[i];
    }

    int cnt = 0;
    for (int i = 1; i <= n; ++ i ) {
        if (d[i] == -1) {
            add(i, i + n, a[i]);
        } else {
            cnt ++ ;
            int x, y;
            if (d[i] == 0) {
                x = a[i], y = 0;
            } else {
                x = 0, y = a[i];
            }
            x += K, y += K;
            add(S, i, x);
            add(i, T, y);
        }
    }

    while (m -- ) {
        int u, v;
        cin >> u >> v;
        add(u, v, INF);
        if (d[u] == -1) add(v + n, u + n, INF);
        else add(v + n, u, INF);
    }

    cout << dinic() - cnt * K;

    return 0;
}