这道题是字典树+贪心的思想,一棵树 两个孩子 0 或者 1;
并且参考了这位大神的 点击打开http://blog.csdn.net/u013761036/article/details/33740467
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct Tree
{
Tree *next[2];
}Tree;
void Buid_Tree(char *str,Tree *T)
{
int len = 34;
Tree *q,*p=T;
for(int i = 0 ;i < len ;i ++)
{
int id = str[i] - '0';
if(p -> next[id] == NULL)
{
q = (Tree *) malloc(sizeof(Tree));
for(int j = 0 ;j < 2 ;j ++)
q -> next[j] = NULL;
p ->next[id] = q;
p = p -> next[id];
}
else p = p -> next[id];
}
}
__int64 Find(char *str,Tree *T)
{
int len = 34;
Tree *p = T;
__int64 K = 2;
K <<= 32;
__int64 sum = 0;
for(int i = 0 ;i < len ;i ++)
{
int id = str[i] - '0';
if(p -> next[id] == NULL)
p = p -> next[id ^ 1];
else
{
p = p -> next[id];
sum += K;
}
K = K / 2;
}
return sum;
}
void get_str(char *str ,__int64 num)
{
int t = 34;
str[t] = '\0';
while(num)
{
str[--t] = (num & 1) + '0';
num >>= 1;
}
for(int i = t - 1 ;i >= 0 ;i --)
str[i] = '0';
}
int main ()
{
int i ,t ,n ,m ,cas = 1;
__int64 num;
Tree *T=(Tree *)malloc(sizeof(Tree));
char str[50];
scanf("%d" ,&t);
while(t--)
{
scanf("%d %d" ,&n ,&m);
T->next[0]=T->next[1]=NULL;
while(n--)
{
scanf("%I64d" ,&num);
get_str(str ,num);
Buid_Tree(str,T);
}
printf("Case #%d:\n" ,cas ++);
while(m--)
{
scanf("%I64d" ,&num);
get_str(str ,num);
for(i = 0 ;i < 34 ;i ++)
if(str[i] == '1') str[i] = '0';
else str[i] = '1';
printf("%I64d\n" ,Find(str,T) ^ num);
}
}
return 0;
}
备忘~~~~~~~~~