问题
分析
- 图论建模,有约束关系的连边;可以有多个连通子图
- 异或操作:二进制位 同 或者 不同
- 对于某个连通子图中的数
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){
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;
}