跳到正文

题解

题解:AT_abc396_e [ABC396E] Min of Restricted Sum

dingxiongyue约 4 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 4 分钟
获赞
1

版本

  1. v1当前

题解:AT_abc396_e [ABC396E] Min of Restricted Sum

Description:

给定长度均为 MM 的序列 XX,YY,ZZ,要求在最小化 ∑i=1NAi\sum _ {i = 1} ^ {N} A_i 的前提下构造一个长度为 NN 的数组 AA,满足 AXixor⁡AYi=ZiA_{X_i} \operatorname{xor} A_{Y_i} = Z_i。

Analysis:

考虑转化为图论。

连接一条 XiX_i 与 YiY_i 之间权值为 ZiZ_i 的无向边。钦定起点点权为 00 遍历整张图。遍历过程中:

  • 若一点已被遍历过,则判断两点点权异或值是否等于该边边权,若不相等,则说明该情况无解。
  • 若一点未被遍历过,则更新该点点权为该边权值与另一点点权的异或值。

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

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

Code:

AC记录

C++
#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;
}
原文