运用位运算会比较简单 Binary Numb…

来源:互联网 发布:java queue 编辑:程序博客网 时间:2024/05/16 10:58

Binary Number

Time Limit : 4000/2000ms(Java/Other)   MemoryLimit : 65536/65536K (Java/Other)
Total Submission(s) :20   AcceptedSubmission(s) : 6

Font: Times NewRoman Verdana Georgia

Font Size:  

Problem Description

For 2 non-negative integers x and y, f(x, y) is defined as thenumber of different bits in the binary format of x and y. Forexample, f(2, 3)=1,f(0, 3)=2, f(5, 10)=4. Now given 2 sets ofnon-negative integers A and B, for each integer b in B, you shouldfind an integer a in A such that f(a, b) is minimized. If there aremore 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 eachtest case contains 2 positive integers m and n (0 <m, n ≤ 100), indicating the numbers of integers of the 2 sets A andB, respectively. Then follow (m + n) lines, each of which containsa non-negative integers no larger than 1000000. The first m linesare the integers in set A and the other n lines are the integers inset B.

Output

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

Sample Input

2 5 
5 2 
1000000 
9999 
1423 
3421 
13245 
353

Sample Output

9999 
0
#include<stdio.h>
#include<string.h>
#define MAX 101
int a[MAX],b[MAX];
int data(int num)
{
     int sum=0;
  while(num)
  {
           sum+=num%2;
         num/=2;
     }
   return sum;

}
void solve(int *a,int *b,int m,int n)
{
   int i,j,num,min,temp;
       for(i=1;i<=n;i++)
    {
           min=9999999;
                for(j=1;j<=m;j++)
            {
                   temp=data(a[j]^b[i]);
                               if(min>temp)
                         {
                                   min=temp;
                                   num=a[j];
                           }
                           else if(min==temp)
                          {
                                   num=num>=a[j]?a[j]:num;
                              }
           }
           printf("%d\n",num);
 }
}

int main()
{
        int cas, m, n; 
    int i;
      scanf("%d", &cas);
  while (cas--)
       {
           scanf("%d%d", &m, &n);      
            for (i=1;i<=m;i++)
           {
                   scanf("%d", a+i);
           }
 
                for (i=1;i<=n;i++)
           {
                   scanf("%d",b+i);
            }
           solve(a,b,m,n);
     }
   return 0;
}