二进制位异或—理解

对于两个数字按位异或需要思考的一个问题是:异或后的结果是比原来两个数大还是小?

接下来看一道题:2018年ACM-ICPC亚洲青岛区域竞赛 

K XOR Clique

BaoBao has a sequence a​1​​,a​2​​,...,a​n​​. He would like to find a subset S of {1,2,...,n} such that ∀i,j∈S, a​i​​⊕a​j​​<min(a​i​​,a​j​​) and ∣S∣ is maximum, where ⊕ means bitwise exclusive or.

Input

There are multiple test cases. The first line of input contains an integer T, indicating the number of test cases. For each test case:

The first line contains an integer n (1≤n≤10​5​​), indicating the length of the sequence.

The second line contains n integers: a​1​​,a​2​​,...,a​n​​ (1≤a​i​​≤10​9​​), indicating the sequence.

It is guaranteed that the sum of n in all cases does not exceed 10​5​​.

Output

For each test case, output an integer denoting the maximum size of S.

扫描二维码关注公众号,回复: 3301232 查看本文章

Sample Input

3
3
1 2 3
3
1 1 1
5
1 2323 534 534 5

Sample Output

2
3
2

解析:两个数异或,异或结果是大于还是小于。其实只需要看最大位就OK 了,怎么理解,往下看。

           (1)设a=7  b=5, 7的二进制写法是:a=0111  

                                           5的二进制写法是: b=0101

                    我们发现其实5和7的二进制最高位都是4,相异或后自然最高位就变成了0,其结果会出现比5 和 7 都小的2.

           (2)设a=7 b=3,    7的二进制写法是: a=0111

                                          3的二进制写法是: b=0011

                     我们发现7和3 的二进制位最好位不同,7是4,3是2  ,所以相异或后结果的最高位就会是4,7^3=4大于其中的3.

            因此,当两个数相异或的时候,其最高位相同,则异或后的数就会比原有的数小。应用这个结论就可以很容易的解出此题

         

#include<bits/stdc++.h>
int ans[32];
int n,m,maxn,num;
int main()
{
    cin>>n;
    while(n--){
        cin>>m;
        maxn=0;
        memset(ans,0,sizeof ans);
        for(int j=1;j<=m;j++){
            cin>>num;
            for(int i=30;i>=0;i--){
                if((1<<i)&num){
                    ans[i]++;
                    break;
                }
            }
        }
        for(int i=0;i<=30;i++)maxn=max(maxn,ans[i]);
        cout<<maxn<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35937273/article/details/82724247