题目链接:https://codeforces.com/gym/103427/problem/B
题目思路非常简单,就是对每个二进制位划分二分图。但是这题难点在于卡常,时限是1000ms,如果30遍DFS的话很容易TLE,最好是进行一次DFS,在这一次内进行30的循环,情况会好不少。这里我用BFS不用递归,200+ms可过。
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
int n, m;
struct Node {
int v, w;
};
vector<Node> e[N];
int val[N], fa[N], num[N];
int find(int x) {
return x == fa[x] ? x : fa[x] = find(fa[x]);
}
int main(void) {
// freopen("in.txt", "r", stdin);
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) fa[i] = i, num[i] = 1, val[i] = -1;
for (int i = 0; i < m; i++) {
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
e[u].push_back({v, w});
e[v].push_back({u, w});
int x = find(u), y = find(v);
if (x != y) {
fa[y] = x;
num[x] += num[y];
}
}
long long ans = 0;
for (int i = 1; i <= n; i++) {
if (find(i) != i) continue;
bool ok = true;
int cnt[35] = {0};
val[i] = 0;
queue<int> q;
q.push(i);
while (!q.empty()) {
int u = q.front();
q.pop();
for (int i = 0; i < e[u].size(); i++) {
int v = e[u][i].v, w = e[u][i].w;
if (val[v] != -1) {
if (val[v] != (val[u] ^ w)) {
ok = false;
break;
}
}
else {
val[v] = val[u] ^ w;
q.push(v);
for (int k = 0; k < 30; k++) {
cnt[k] += (val[v] >> k & 1);
}
}
}
if (!ok) break;
}
if (!ok) {
ans = -1;
break;
}
for (int k = 0; k < 30; k++) {
ans += (1LL << k) * min(cnt[k], num[i] - cnt[k]);
}
}
printf("%lld\n", ans);
return 0;
}