标签:字典树
#include<stdio.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
typedef struct tire{
__int64 w; //从根节点到该结点的
struct tire *next[2]; //每个节点下面可能有2个数,0和1
}tree,*tiretree; /* 字典树的存储结构 */
tiretree T;
void insert(__int64 a) //把a的32位二进制码插入到字典树中
{
int i;
tiretree q,p;
q=T;
for(i=31;i>=0;i--)
{
if(!(a&1<<i)) //若为0就插入到第一个子结点,a的32位二进制码是按高位往地位从根节点到叶子结点存放的;
{
p=q->next[0];
if(p==NULL) //如果该二进制数应该在的位置为空,则将二进制数插入到该位置
{
p=(tiretree)malloc(sizeof(tree));
p->next[0]=NULL;
p->next[1]=NULL;
if(i==0) //若a结点达到叶子节点,就把a存到叶子结点中;
p->w=a;
else
p->w=0; //若为a的中间经过结点,则不赋值;即字典树中只有叶子结点有数字,其余结点都为0;
q->next[0]=p;
}
q=p;
}
else
{
p=q->next[1]; //若为1就插入到第二个子结点,
if(p==NULL)
{
p=(tiretree)malloc(sizeof(tree));
p->next[0]=NULL;
p->next[1]=NULL;
if(i==0)
p->w=a;
else
p->w=0;
q->next[1]=p;
}
q=q->next[1]; //如果该二进制应该在的位置不空,则继续比较下一个二进制
}
}
}
__int64 find(__int64 a) // 对于任意非负整数x,可以沿着树根往下贪心找到y,使得a异或y最大,复杂度为树的深度。
{
int i;
tiretree q;
q=T;
for(i=31;i>=0;i--)
{
if(q->next[0]==NULL)
q=q->next[1];
else
if(q->next[1]==NULL)
q=q->next[0];
else
if((a&1<<i)==0)
q=q->next[0];
else
q=q->next[1];
}
return q->w;
}
int main()
{
int n,i,p,TT,count=0;
__int64 max,a,m,q;
scanf("%d",&TT);
while(TT--)
{
scanf("%d %d",&n,&p);
delete(T);
T=(tiretree)malloc(sizeof(tree)); //构造单个根结点
T->next[0]=NULL;
T->next[1]=NULL;
T->w=0;
max=0;
for(i=0;i<n;i++)
{
scanf("%I64d",&a);
insert(a); //分别把集合中的每个数插入到树中
}
for(i=0;i<p;i++)
{
scanf("%I64d",&q);
m=~q; //然后把要比较的数取反后,与字典树中存的数进行比较
if(i==0)
printf("Case #%d:\n",++count);
printf("%I64d\n",find(m));
}
}
return 0;
}2014百度之星资格赛—— Xor Sum(01字典树),布布扣,bubuko.com
标签:字典树
原文地址:http://blog.csdn.net/u010270403/article/details/26292587