NOI2014 洛谷P2114 起床困难综合征(位运算)
呃...这道题算是noi中比较简单的题吧......
众所周知,位运算是个好东西,它就是对应的位进行运算,跟其他的位没有关系。
我们要选取一个m值使最后的攻击力最大,对于这个m,从高位开始枚举,判断该位选0更优还是选1更优,怎么判断呢?把该位进行n次运算不就行了吗,看最后的数是1还是0。
.................位运算中的DP?
1 #include<bits/stdc++.h> 2 using namespace std; 3 pair<string,int> a[100005]; 4 int n,m; 5 6 int calc(int bit,int now){//用参数的第bit位进行n次运算 7 for(int i=1;i<=n;i++){ 8 int x=a[i].second>>bit&1;//取出第bit位的数 9 if(a[i].first=="AND") now&=x; 10 else if(a[i].first=="OR") now|=x; 11 else now^=x; 12 } 13 return now; 14 } 15 16 int main(){ 17 cin>>n>>m; 18 for(int i=1;i<=n;i++){ 19 char str[5];int x; 20 scanf("%s%d",&str,&x); 21 a[i]=make_pair(str,x); 22 } 23 int val=0,ans=0; 24 for(int bit=29;bit>=0;bit--){//从高位枚举 25 int res0=calc(bit,0); 26 int res1=calc(bit,1); 27 if(val+(1<<bit)<=m && res0<res1){ 28 val+=1<<bit,ans+=1<<bit;//该位填1更优 29 } 30 else ans+=res0<<bit;//该位填0更优 31 } 32 cout<<ans<<endl; 33 }