2021年ICPC(沈阳)Bitwise Exclusive-OR Sequence(图论)

问题

分析

  • 图论建模,有约束关系的连边;可以有多个连通子图
  • 异或操作:二进制位 同 或者 不同
  • 对于某个连通子图中的数 a i a_i ai,它的某一位,要么取1,要么取0;根据约束关系,可以确定子图中的其它数的相应位的取值;若冲突,则意味着约束无法满足;
  • 对于 a i a_i ai的某一位,取1时有解,则取0时也有解;可以调节0或1的取值,从而达到和最小

代码

#include <bits/stdc++.h>
using namespace std;
const int mxn = 100010;
int n, m, a[mxn], h[mxn], vis[mxn], tot = 0;
struct Edge{ int to, w, nxt;} edg[mxn<<2];
void add(int u, int v, int w){
    edg[++tot].nxt = h[u], h[u] = tot, edg[tot].w = w, edg[tot].to = v;
}
int main(void){
    int u, v, w;
    long long ans = 0;
    queue<int> q;
    vector<int> vt;
    memset(h, -1, sizeof h);
    memset(vis, 0, sizeof vis);
    scanf("%d%d", &n, &m);
    while(m--) scanf("%d%d%d", &u, &v, &w), add(u, v, w), add(v, u, w);
    for(int i = 1; i <= n; ++i){
        if(vis[i]) continue;
        if(!vt.empty()) vt.clear();
        a[i] = 0, q.push(i), vis[i] = 1, vt.push_back(i);
        while(!q.empty()){
            u = q.front(), q.pop();
            for(int j = h[u]; ~j; j = edg[j].nxt){
                v = edg[j].to, w = edg[j].w;
                if(!vis[v]) a[v] = w^a[u], q.push(v), vis[v] = 1, vt.push_back(v);
                else if((a[v]^a[u]) != w){ // 注意:运算优先级,括号不能少,错误点
                    printf("-1\n");
                    return 0;
                }
            }
        }
        for(int i = 0; i < 30; ++i){ // 同一个连通子图中,进行01调节
            int bit = 1 << i, cnt = 0;
            tot = vt.size();
            for(int j = 0; j < tot; ++j) if(a[vt[j]] & bit) ++cnt;
            ans += 1LL*min(cnt, tot-cnt)*bit;
        }
    }
    printf("%lld\n", ans);
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

jpphy0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值