题意:给出n个数,m次查询,给出一个数x,每次在n个数中找出与x异或值最大的那个数
思路:首先建立字典树,只有0和1两个分支,在查询的时候,这个数在某一位为1的话就向0的方向查询,为0的话就向1的方向查询,前提必须存在,字典树的最后记录每一个分支所代表的数值
#include <iostream>
#include <cstdio>
using namespace std;
struct node{
int num;
node *next[2];
};
void add(node *head,int num){
node *p = head;
for(int i = 31; i >= 0; i--){
int k = (num >> i) & 1;
if(p -> next[k] == NULL){
node *q = new node();
p -> next[k] = q;
}
p = p -> next[k];
}
p -> num = num;
}
int find(node *head,int num){
node *p = head;
for(int i = 31; i >= 0; i--){
int k = (num >> i) & 1;
if(p -> next[k ^ 1] != NULL){
p = p -> next[k ^ 1];
}
else{
p = p -> next[k];
}
}
return p -> num;
}
int main(void){
int t,n,m;
scanf("%d",&t);
int cnt = 0;
while(t--){
node *head = new node();
scanf("%d%d",&n,&m);
int num;
for(int i = 1; i <= n; i++){
scanf("%d",&num);
add(head,num);
}
printf("Case #%d:\n",++cnt);
for(int i = 1; i <= m; i++){
scanf("%d",&num);
int a = find(head,num);
printf("%d\n",a);
}
}
return 0;
}