HDU 4825 01字典树

http://acm.hdu.edu.cn/showproblem.php?pid=4825

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

思路:01字典树模板题。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<cmath>
#include<map>
#include<algorithm>
#define INF 0x3f3f3f3f
typedef long long ll;
using namespace std;

int tree[1600000][2];
int a[35];
int tot;

void to2(int n)//把n转换成二进制的形式 高位为0
{
    memset(a,0,sizeof(a));
    int len=0;
    while(n>0)
    {
        a[len++]=n&1;
        n>>=1;
    }
}

void Insert()
{
    int root=0;
    for(int i=31;i>=0;i--)//32为整数 从高位到低位插入
    {
        int id=a[i];
        if(!tree[root][id])
            tree[root][id]=++tot;
        root=tree[root][id];
    }
}

ll query()
{
    int root=0;
    ll temp=0;
    for(int i=31;i>=0;i--)
    {
        int id=1-a[i];//贪心
        if(tree[root][id])//存在我们要找的节点
        {
            if(id==1)
                temp=temp<<1|1;
            else
                temp<<=1;
            root=tree[root][id];
        }
        else//不存在
        {
            if(id==1)
                temp<<=1;
            else
                temp=temp<<1|1;
            root=tree[root][1-id];
        }
    }
    return temp;
}

int main()
{
    int t;
    scanf("%d",&t);
    int n,m;
    int times=0;
    while(t--)
    {
        scanf("%d %d",&n,&m);
        memset(tree,0,sizeof(tree));
        tot=0;
        int temp;
        for(int i=0;i<n;i++)
        {
            scanf("%d",&temp);
            to2(temp);
            Insert();
        }
        printf("Case #%d:\n",++times);
        for(int i=0;i<m;i++)
        {
            scanf("%d",&temp);
            to2(temp);
            printf("%lld\n",query());
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/xiji333/article/details/88752791