题解 P16964 [SCCPC 2026] 最大权独立集问题
前言
不要被“最大权独立集”吓到了哦!
分析
观察发现:
两数异或后
证明:
- 对于两个数
a 和b ,它们异或后1 的个数为奇数; - 等价于
\text{popcount}(a \oplus b) \bmod 2 = 1 ; - 由于
\text{popcount}(a \oplus b) \equiv \text{popcount}(a) + \text{popcount}(b) \pmod{2} (因为异或运算在每一位上相当于模2 加法); - 所以
\text{popcount}(a \oplus b) \equiv \text{popcount}(a) \oplus \text{popcount}(b) \pmod{2} 。
设有两个集合:
那么:
- 偶点
\oplus 偶点\rightarrow \text{popcount} 为偶数\rightarrow 无边; - 奇点
\oplus 奇点\rightarrow \text{popcount} 为偶数\rightarrow 无边; - 偶点
\oplus 奇点\rightarrow \text{popcount} 为奇数\rightarrow 有边。
所以这个图是一个完全二分图,两个部分分别为偶点集和奇点集。
最大权独立集
在这个二分图中,独立集不能同时包含偶点和奇点,因为任意一个偶点和一个奇点之间都有边。
因此独立集要么全选偶点,要么全选奇点。
所以最大权独立集的权值
代码实现
#include <bits/stdc++.h>
using namespace std;
#define ll long long
int t, n;
ll w, sum0, sum1;
int popcount(ll x) {
int cnt = 0;
while (x) {
cnt += x & 1, x >>= 1;
}
return cnt;
}
int main() {
cin >> t;
while (t--) {
cin >> n;
sum0 = sum1 = 0;
for (int i = 0; i < n; i++) {
cin >> w;
if (popcount(w) % 2 == 0) {
sum0 += w;
} else {
sum1 += w;
}
}
cout << max(sum0, sum1) << endl;
}
return 0;
}