题解:AT_abc396_e [ABC396E] Min of Restricted Sum
dingxiongyue · · 题解
题解:AT_abc396_e [ABC396E] Min of Restricted Sum
Description:
给定长度均为
Analysis:
考虑转化为图论。
连接一条
- 若一点已被遍历过,则判断两点点权异或值是否等于该边边权,若不相等,则说明该情况无解。
- 若一点未被遍历过,则更新该点点权为该边权值与另一点点权的异或值。
最后枚举二进制位数,遍历所有点,统计所有点权在二进制下第
时间复杂度
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;
}