[HDU] 3711 Binary Number [位运算]

Binary Number

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


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.
 

题解:定义函数f(x,y)表示非负整数x,y二进制对应位上不同数字个数。求在集合B中所有整数bi在集合A中找一个对应的数ai,使得f(ai,bi)最小,如果f(ai,bi)相等,使ai尽量小。

因为0 < m, n ≤ 100,所以直接O(nm)暴力扫一遍,直接ci=ai xor bi然后统计二进制ci上1的个数,求ci末尾是否为1直接判断ci是否为奇数即可,然后ci>>=1,右移一位。

代码:

 1 #include<cstdio>
 2 #include<algorithm>
 3 
 4 const int INF=1e9+3;
 5 using namespace std;
 6 
 7 int main()
 8 {
 9     int T,i,j,p,a[110],b[110],minn,minx,num,m,n;
10     
11     scanf("%d",&T);
12     while(T--) {
13         scanf("%d%d",&m,&n);
14         for(int i=0;i<m;i++) {
15             scanf("%d",&a[i]);
16         }
17         for(int i=0;i<n;i++) {
18             scanf("%d",&b[i]);
19         }
20        
21         for(i=0;i<n;i++)
22         {
23             minn=INF;minx=INF;
24             for(j=0;j<m;j++) {
25                  num=0;
26                  p=a[j] xor b[i];
27                  while(p>0) {
28                     if(p%2!=0) num++;
29                     p>>=1;
30                  }      
31                 if(num<minn) { minx=a[j];minn=num;}
32                 else if(num==minn && a[j]<minx)  minx=a[j];
33             }
34             
35             printf("%d
",minx);
36         }
37     }
38         
39     
40     return 0;
41 }
原文地址:https://www.cnblogs.com/sxiszero/p/4087516.html