HDU 3711 Binary Number

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU 3711 Binary Number相关的知识,希望对你有一定的参考价值。

Binary Number

Time Limit: 4000/2000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1879    Accepted Submission(s): 1133


Problem Description
For 2 non-negative integers x and y, f(x, y) is defined as the number of different bits in the binary format of x and y. For example, f(2, 3)=1,f(0, 3)=2, f(5, 10)=4. Now given 2 sets of non-negative integers A and B, for each integer b in B, you should find an integer a in A such that f(a, b) is minimized. If there are more than one such integer in set A, choose the smallest one.
 

 

Input
The first line of the input is an integer T (0 < T ≤ 100), indicating the number of test cases. The first line of each test case contains 2 positive integers m and n (0 < m, n ≤ 100), indicating the numbers of integers of the 2 sets A and B, respectively. Then follow (m + n) lines, each of which contains a non-negative integers no larger than 1000000. The first m lines are the integers in set A and the other n lines are the integers in set B.
 

 

Output
For each test case you should output n lines, each of which contains the result for each query in a single line.
 

 

Sample Input
2
2 5
1
2
1
2
3
4
5
5 2
1000000
9999
1423
3421
0
13245
353
 

 

Sample Output
1
2
1
1
1
9999
0
 

 

Author
CAO, Peng
 

 

Source
 
 
 
解析:本题考查位运算。关键在于求x和y的二进制不同位的个数,即x^y的二进制中1的个数。可以用如下方法快速求出:
int cal(int x)
{
    int cnt = 0;
    while(x){
        ++cnt;
        x &= (x-1);
    }
    return cnt;
}
这段代码的核心在于每执行一次x &= (x-1),会将x的二进制中最低位的1变为0。
运用这个原理,我们还可以得到判断一个正整数x是否为2的n(n>=0)次幂的方法:如果(x&(x-1)) == 0,则为true;否则为false。
常用的位运算还有x&1、x&(-x)等。
x&1:x为奇数则结果为1,x为偶数则结果为0。
x&(-x):取出x的二进制中低位起,第一个1所在位置代表的数(若x的二进制中不存在1,即x为0,结果为0)。
 
 
 
 1 #include <cstdio>
 2 #include <algorithm>
 3 using namespace std;
 4 
 5 int T;
 6 int m,n;
 7 int A[105],b;
 8 
 9 int cal(int x)
10 {
11     int cnt = 0;
12     while(x){
13         ++cnt;
14         x &= (x-1);
15     }
16     return cnt;
17 }
18 
19 int main()
20 {
21     scanf("%d",&T);
22     while(T--){
23         scanf("%d%d",&m,&n);
24         for(int i = 0; i<m; ++i)
25             scanf("%d",&A[i]);
26         sort(A,A+m);
27         for(int i = 0; i<n; ++i){
28             scanf("%d",&b);
29             int min_cnt = 0x7fffffff;
30             int ans;
31             for(int j = 0; j<m; ++j){
32                 int cnt = cal(b^A[j]);
33                 if(cnt<min_cnt){
34                     min_cnt = cnt;
35                     ans = A[j];
36                 }
37             }
38             printf("%d\n",ans);
39         }
40     }
41     return 0;
42 }

 

以上是关于HDU 3711 Binary Number的主要内容,如果未能解决你的问题,请参考以下文章

HDU 1950(LIS)

hdu3371 Connect the Cities (MST)

HDU2848 Number Cutting Game

规律贪心数学HDU 5573 Binary Tree

hdu 5573---Binary Tree(构造)

Binary Tree Traversals HDU - 1710 ?