HDU-4825 Xor Sum(字典树求异或最大值)

题目链接:点此

我的github地址:点此

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
 
Source
 
题目意思:就是跟你n个数,然后m次询问,每次询问给你一个数k,求n个数中与k异或值最大的那个数
 
一般遍历的话,肯定容易T
所以我们可以建立一个字典树,每个分支为0,或1
 
 
/*
    data:2018.04.26
    author:gswycf
    link:http://acm.hdu.edu.cn/showproblem.php?pid=4825
    accout:tonysave
*/
#define ll long long
#define IO ios::sync_with_stdio(false);
#define maxn 100005

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<math.h>
#include<string.h>
#include<vector>
using namespace std;
class Node
{
    public:
        int a[2];
        ll v;
};
Node node[32*maxn];int cnt=0;
void init()
{
    cnt=0;
    memset(node,0,sizeof(node));
}
void update(ll num)
{
    int p=0;
    for(int i=32;i>=0;i--)
    {
        int c=((num>>i)&1);
        if(!node[p].a[c])
            node[p].a[c]=++cnt;
        p=node[p].a[c];
    }
    node[p].v=num;
}
ll query(ll num)
{
    int p=0;
    for(int i=32;i>=0;i--)
    {
        int c=((num>>i)&1);
        if(node[p].a[(c^1)])p=node[p].a[(c^1)];
        else p=node[p].a[c];
    }
    return node[p].v;
}
int main()
{
    int ca,n,m;ll tem;
    while(~scanf("%d",&ca))
    {
        for(int i=1;i<=ca;i++)
        {
            init();
            scanf("%d%d",&n,&m);
            for(int j=1;j<=n;j++)
            {
                scanf("%lld",&tem);
                update(tem);
            }
            printf("Case #%d:\n",i);
            for(int j=1;j<=m;j++)
            {
                scanf("%lld",&tem);
                printf("%lld\n",query(tem));
            }
        }
    }
}

注意几点:

(1)要用ll,因为int右移32位会出现问题

(2)init()函数要每个case都要调用

(ps:因为这两个错误,卡了一个小时,ORZ。。。。。)

猜你喜欢

转载自www.cnblogs.com/fantastic123/p/8954943.html