【CF 1017(Div.4) E】位运算懵逼中

题目描述

博尼卡-安巴拉布给你一个由 \(n\) 个整数 \(a_1,a_2,\ldots,a_n\) 组成的序列。

请输出所有 \(1 \leq k \leq n\)\((a_k\oplus a_1)+(a_k\oplus a_2)+\ldots+(a_k\oplus a_n)\) 的最大值。注意 \(\oplus\) 表示 bitwise XOR 运算

输入格式

第一行包含一个整数 \(t\) ( \(1 \leq t \leq 10^4\) ) - 独立测试用例的数量。

每个测试用例的第一行包含一个整数 \(n\) ( \(1 \leq n\leq 2\cdot 10^5\) )--测试用例的长度。( \(1 \leq n\leq 2\cdot 10^5\) ) - 数组长度。

每个测试用例的第二行包含 \(n\) 个整数 \(a_1,a_2,\ldots,a_n\) ( \(0 \leq a_i < 2^{30}\) )。

保证所有测试用例中 \(n\) 的总和不超过 \(2\cdot 10^5\)

输出格式

对于每个测试用例,在新行中输出最大值。

样例输入

5
3
18 18 18
5
1 2 4 8 16
5
8 13 4 5 15
6
625 676 729 784 841 900
1
1

样例输出

0
79
37
1555
0

提示

在第一个测试案例中,我们能做的最好的是 \((18\oplus18)+(18\oplus18)+(18\oplus18)=0\)

在第二个测试案例中,我们选择 \(k=5\) ,得到 \((16\oplus1)+(16\oplus2)+(16\oplus4)+(16\oplus8)+(16\oplus16)=79\)

解法&&个人感想

这道题其实是看着题解补的,因为位运算的题目其实不大会做
这道题还是有点思路,分点讨论
当时看到题解是惊为天人,原来还能这么写
众所周知,作为之前写二进制只会用数组预存的(甚至去模2),写这道题确实被震撼了
用位运算口牙!直接1<<j a[i]>>j
然后我就死活过不去 一看 define int long long 和signed main()就要气晕
以后我也这么写好了()
还有vectorcnt(30,0) 不是,既然vector可以直接扩充,定大小
那我传统数组是干嘛的
这不就相当于把芙蓉王扔了抽锐刻五吗
下面看代码,太简洁了:

#include<bits/stdc++.h>
#define ull unsigned long long
#define int long long
using namespace std;
int t;
int n;
int a[200005];
signed main(){
    scanf("%d",&t);
    while(t--){
        int ans=0;
        vector<int>cnt(30,0);
        cin>>n;
        for(int i=1;i<=n;i++){
            cin>>a[i];
            for(int j=0;j<=29;j++){
                cnt[j]+=((a[i]>>j)&1);
            }
        }
        for(int i=1;i<=n;i++){
            int tot=0;
            for(int j=0;j<=29;j++){
                bool flag=((a[i]>>j)&1);
                if(flag) tot+=(1<<j)*(n-cnt[j]);
                else tot+=(1<<j)*cnt[j];
            }
            ans=max(tot,ans);
        }
        cout<<ans<<endl;
    }
    system("pause");
    return 0;
}
posted @ 2025-04-17 16:05  elainafan  阅读(56)  评论(0)    收藏  举报