题解:P16964 [SCCPC 2026] 最大权独立集问题

· · 题解

思路

定义函数 \operatorname{parity}(n) 为 n 在二进制下 1 的个数是否为奇数。

有定理:

\operatorname{parity}(x \oplus y)=\operatorname{parity}(x) \oplus \operatorname{parity}(y)

所以我们只需要把每个 W_i 分到两个组别去,一类满足 W_i 二进制下 1 的个数为奇数,另一类满足为偶数。对于每一类内,显然不存在边,符合要求。

对两类分别求和取最大值即可。

Code

#include<bits/stdc++.h>
using namespace std;
int T,n;
int main(){
    ios::sync_with_stdio(0),cin.tie(0);
    cin>>T;
    while(T--){
        cin>>n;
        long long s1=0,s2=0;
        while(n--){
            int w;cin>>w;
            if(__builtin_parity(w)) s1+=w;
            else s2+=w;
        }
        cout<<max(s1,s2)<<'\n';
    }
}