"尚学堂杯"哈尔滨理工大学第七届程序设计竞赛 G(2331) Great Atm(二进制)(思路)

来源:互联网 发布:天天动听软件官方下载 编辑:程序博客网 时间:2024/05/16 12:26

Great Atm

Description
An old story said the evil dragon wasn’t evil at all, only bewitched, and now that the riddles were solved it was proving to be as kind as its new master.
A powerful warrior Atm is going to solve the riddles. First, he should beat the evil wizard. The road from Atm’s castle to wizard’s lab is filled with magic traps. The magic trap will affect Atm’s combat effectiveness.
Atm’s combat effectiveness can be considered as an integer. Effect of magic trap can be considered as mathematical operation. The three kinds of magic traps correspond to three kind of bit operation. (AND, OR and XOR)
Atm can adjust his equipment to change his initial combat effectiveness from 0 to m (include 0 and m). He wants when he arrives the wizard’s lab, his combat effectiveness can be maximum.
Input
There are multiple test cases.
For each test cases:
The first line contains two integers n(1<=n<=10^5) and m(1<=m<=10^9), indicating the number of magic traps and the maximum of initial combat effectiveness.
Each of the next n lines contains a string and an integer, indicating the bit operation. The string will be “AND”, “OR” or “XOR” correspond to AND operation (&), OR operation (|) or XOR operation (^). The integer t(1<=t<=10^9) is second operand in the operation.

Output
For each test cases, a line contains an integer, indicating the maximum combat effectiveness when he arrives the wizard’s lab.
Sample Input
3 10
AND 5
OR 6
XOR 7
Sample Output
1
Source
“尚学堂杯”哈尔滨理工大学第七届程序设计竞赛


题意:有m+1个数,分别是0~m,从中选取一个数进行n轮(&,|,^)操作后使得最后的结果最大,并输出这个结果

思路:暴力肯定超时i,所以要想一下特殊的数。而题目和二进制有关,所以肯定要在二进制上动手了,
可以想到二进制的每一位只可能是0或1,而每一位为0或为1最后所产生的结果都有可能不同。

所以我们可以先求出二进制的每一位都为0(十进制为0)进行n轮操作所得的结果和二进制的每一位都为1(十进制为2147483647)进行n轮操作所得的结果,并且分别记录下出所得结果的二进制上每一位的数。

最后遍历二进制的31位,如果原先这一位为0,但操作后的结果中这一位为1,那么最后的答案肯定要加上这一位(≤m的数中这一位肯定可以为0);
如果原先这一位为1,操作后的结果中这一位也为1,此时我们要先判断这一位的十进制是否大于m,如果不大于那么最后答案也要加上这一位(因为≤m的数中这一位可以为1),最后加得的答案就是最终的结果了

代码:

#include<stdio.h>int temp[40][2];int main(){    int n,m,x;    char s[10];    while(~scanf("%d%d",&n,&m))    {        int Max=2147483647,Min=0;        for(int i=0; i<n; ++i)        {            scanf("%s %d",s,&x);            if(s[0]=='A')                Max&=x,Min&=x;            else if(s[0]=='O')                Max|=x,Min|=x;            else if(s[0]=='X')                Max^=x,Min^=x;        }        for(int i=30; ~i; --i)//记录二进制的每一位为0或为1时所得的(二进制中这一位的)结果        {            temp[i][0]=(Min&(1<<i));            temp[i][1]=(Max&(1<<i));        }        int ans=0;        for(int i=30; ~i; --i)        {            if(temp[i][0])                ans=ans|(1<<i);            else if(temp[i][1])            {                if((1<<i)<=m)                {                    ans=ans|(1<<i);                    m-=(1<<i);                }            }        }        printf("%d\n",ans);    }    return 0;}
2 0