hdu-4825-Xor Sum(字典树,二进制)

Xor Sum

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 132768/132768 K (Java/Others)
Total Submission(s): 3264    Accepted Submission(s): 1408


Problem Description
Zeus 和 Prometheus 做了一个游戏,Prometheus 给 Zeus 一个集合,集合中包含了N个正整数,随后 Prometheus 将向 Zeus 发起M次询问,每次询问中包含一个正整数 S ,之后 Zeus 需要在集合当中找出一个正整数 K ,使得 K 与 S 的异或结果最大。Prometheus 为了让 Zeus 看到人类的伟大,随即同意 Zeus 可以向人类求助。你能证明人类的智慧么?
 

Input
输入包含若干组测试数据,每组测试数据包含若干行。
输入的第一行是一个整数T(T < 10),表示共有T组数据。
每组数据的第一行输入两个正整数N,M(<1=N,M<=100000),接下来一行,包含N个正整数,代表 Zeus 的获得的集合,之后M行,每行一个正整数S,代表 Prometheus 询问的正整数。所有正整数均不超过2^32。
 

Output
对于每组数据,首先需要输出单独一行”Case #?:”,其中问号处应填入当前的数据组数,组数从1开始计算。
对于每个询问,输出一个正整数K,使得K与S异或值最大。
 

Sample Input
  
  
2 3 2 3 4 5 1 5 4 1 4 6 5 6 3
 

Sample Output
  
  
Case #1: 4 3 Case #2: 4
 
思路:
将所有的数都化为  32 位的进制 不够前补 0  从高位  为根开始建树  (查找时从高位查找) 异或值最大  不同为1 相同为 0 ,如果有不同的走不同的没有则走相同的,从高位开始 这样就能查找到最大的。。
code:
#include<iostream>
#include<cstdio>
using namespace std;
struct node
{
    int cut;
    node *son[2];
    node (){
        cut=0;
        son[0]=son[1]=NULL;
    }
};
node *root;
void Insert(int x)  ///建字典树
{
    bool a[32];
    int xx=x;
    node *p=root,*q;
    for(int i=0;i<32;i++){///将传入的数化成二进制
        a[i]=x&1;
        x>>=1;
    }
    for(int i=31;i>=0;i--){///倒着建树  查找时从高位开始
        if(p->son[a[i]]!=NULL){
            p=p->son[a[i]];
        }else{
            q=new node ;
            p->son[a[i]]=q;
            p=q;
        }
    }
    p->cut=xx;  ///将值存在结束位置
}
int Find(int x)  ///查找
{
    bool a[32];
    node *p=root;
    for(int i=0;i<32;i++){
        a[i]=x&1;
        x>>=1;
    }
    for(int i=31;i>=0;i--){
        if(p->son[!a[i]]!=NULL) p=p->son[!a[i]];  ///求异或最大  如果有不同的先走不同的
        else p=p->son[a[i]];
    }
    return p->cut;
}
void del(node *p)  ///销毁字典树
{
    for(int i=0;i<2;i++)
        if(p->son[i]!=NULL) del(p->son[i]);
    delete(p);
}
int main()
{
    int t,n,m,k;
    scanf("%d",&t);
    for(k=1;k<=t;k++){
        scanf("%d%d",&n,&m);
        int x;
        root=new node;
        for(int i=0;i<n;i++){
            scanf("%d",&x);
            Insert(x);
        }
        printf("Case #%d:\n",k);
        for(int i=0;i<m;i++){
            scanf("%d",&x);
            printf("%d\n",Find(x));
        }
        del(root);
    }
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值