51nod 1315 合法整数集

来源:互联网 发布:读出文字的软件 编辑:程序博客网 时间:2024/06/02 02:21

先从数字中去掉与X进行或运算结果不为X的数字,因为这样的数字肯定在X的某些个为0的位置上数值为1,无论如何也是去不掉的。
然后计算出X的二进制位哪些位置为1,然后从剩下那堆数字中计算X为1的位置那些数字在相应位置也为1的数字的个数。比如X二进制位的第二位为1,就计算出那些数字中有几个数字第二位为1。如果X的每个为1的位置所对应的数字个数都不为0,则一定能够通过或运算计算出X。从中选出最小的就是结果。如果有些个数为0的,则无法或运算得出X,结果就是0

#include <bits/stdc++.h>using namespace std;typedef long long LL;LL num[55];LL X;LL numcnt;int calen(LL num){    return log(num)/log(2)+1;}int main(){    ios::sync_with_stdio(false);    cin.tie(0);    int N;    LL tn;    cin >> N >> X;    int xlen = calen(X);    for(int i = 0; i < N; ++i)    {        cin >> tn;        if((tn|X) == X)            num[numcnt++] = tn;    }    int res = 55;    for(int i = 0; i < xlen; ++i)    {        LL temp = 1<<i;        if(!(temp&X))continue;        int cnt = 0;        for(int j = 0; j < numcnt; ++j)        {            if(temp&num[j])                ++cnt;        }        if(cnt == 0)        {            cout << 0 << endl;            return 0;        }        if(cnt < res)            res = cnt;    }    cout << res << endl;    return 0;}