题意:
思路:
在位运算的视角中,我们要让一个数尽可能大,那么八成需要用到【按位贪心】
即一个数要可能大,就从它的最高位到最低位贪心,能变1就变1
这道题中,我们要让和尽可能大,就要让每一个数都尽可能大
对于每一个数来说:
我们就从大到小一位一位地进行考虑
对于最高位,如果区间[l,r]中的数最高位1比较多,那么x最高位最好是0,否则x最高位最好是1
在接下来的位上都可以这样考虑
因此我们需要维护一个区间内某一位上1的个数和0的个数
n方枚举显然超时
因此前缀和维护一下就行
Code:
#include <bits/stdc++.h>
using namespace std;
const int mxn=1e5+10;
int n,q;
int a[mxn],b[mxn][35];
int main(){
scanf("%d",&n);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
for(int j=30;j>=0;j--){
for(int i=1;i<=n;i++){
if(a[i]&(1<<j)) b[i][j]=1;
}
}
for(int j=30;j>=0;j--){
for(int i=1;i<=n;i++){
b[i][j]+=b[i-1][j];
}
}
scanf("%d",&q);
int l,r;
while(q--){
int x=0;
scanf("%d%d",&l,&r);
for(int j=30;j>=0;j--){
int cnt1=b[r][j]-b[l-1][j];
int cnt0=(r-l+1-cnt1);
if(cnt0>cnt1) x|=(1<<j);
}
printf("%d\n",x);
}
return 0;
}
总结:
bitmask中要使数尽可能大,很可能是用按位贪心