题解:AT_abc396_e [ABC396E] Min of Restricted Sum

· · 题解

题解:AT_abc396_e [ABC396E] Min of Restricted Sum

Description:

给定长度均为 M 的序列 X,Y,Z,要求在最小化 \sum _ {i = 1} ^ {N} A_i 的前提下构造一个长度为 N 的数组 A,满足 A_{X_i} \operatorname{xor} A_{Y_i} = Z_i。

Analysis:

考虑转化为图论。

连接一条 X_i 与 Y_i 之间权值为 Z_i 的无向边。钦定起点点权为 0 遍历整张图。遍历过程中:

最后枚举二进制位数,遍历所有点,统计所有点权在二进制下第 k 位的 1 的个数,根据 1 的个数讨论该位是否填 0。

时间复杂度 O(N + M + \log \max _ {i = 1} ^ {N} A_i)。

Code:

AC记录

#include <iostream>
#include <cstring>
#include <vector>
#define int long long
const int N = 2e5 + 10;
int n, m;
int a, b, c;
int ans[N];
int num[N];
int e[N], h[N], ne[N], w[N], idx;
bool vis[N];
std::vector<int> res;
inline int read() {
    int x = 0, f = 1;
    char ch = getchar();
    while (!isdigit(ch)) {
        if (ch == '-') f = -1;
        ch = getchar();
    }
    while (isdigit(ch)) {
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    return x * f;
}

inline void write(int x) {
    if (x < 0) putchar('-'), x = -x;
    if (x > 9) write(x / 10);
    putchar(x % 10 + '0');
}

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

void dfs(int u) {
    res.push_back(u); 
    for (int i = h[u]; ~i; i = ne[i]) {
        int j = e[i];
        if (vis[j]) {
            if ((num[j] ^ num[u]) != w[i]) {
                puts("-1");
                exit(0);
            }
            continue;
        }
        vis[j] = true;
        num[j] = w[i] ^ num[u];
        dfs(j);
    }
}

signed main() {
    memset(h, -1, sizeof h);
    n = read(), m = read();
    while(m--) {
        a = read(), b = read(), c = read();
        add(a, b, c), add(b, a, c);
    }
    for (int i = 1; i <= n; i++) {
        if (vis[i]) continue;
        vis[i] = true;
        num[i] = 0;
        res.clear();
        dfs(i);
        for (int k = 0; k <= 30; k++) {
            int cnt = 0;
            for (auto j : res) 
                if (num[j] & (1 << k)) cnt++;
            if (cnt < res.size() - cnt) {
                for (auto j : res) 
                    if (num[j] & (1 << k)) 
                        ans[j] |= (1 << k);
            } else {
                for (auto j : res) 
                    if (!(num[j] & (1 << k))) 
                        ans[j] |= (1 << k);
            }
        }
    }
    for (int i = 1; i <= n; i++) 
        write(ans[i]), putchar(' ');
    printf("\n");
    return 0;
}