[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\n",minx);
36         }
37     }
38         
39     
40     return 0;
41 }

 

转载于:https://www.cnblogs.com/sxiszero/p/4087516.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值