Xor Sum

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

题目大意 :在一组给定的数值中,给出一个数,在集合中找到和它异或值最大的那个数。

题目分析 :我们无非存两个数 1 或 0,这个树里面无非就是左子树和右子树,这样其实将这棵树说成是二叉树也不为过,但我们今天用字典树的模板去做这道题。数的建立是小菜

一碟,难点就在我们如何寻找这个值是的异或最大(我还没想到怎么讲,先贴代码吧!)

题目收获 :建树的多样性。

AC代码:
#include <iostream>
#include <algorithm>
const int LEN = 2;
using namespace std;
typedef long long ll;
const int maxn = 100000;
typedef struct tire
{
    struct tire *next[LEN];
}tire;


void get_char(char *time,ll mid)
{
    int len = 32 + 2;//题目说数最大不超过2的32次方,所以树的高度我们就设为34;
    time[len] = '';//字符最后为结束符号
    while (mid)//得到二进制的mid
    {
        time[--len] = (mid & 1) + '0';
        mid >>= 1;
    }
    for (int i = len - 1; i >= 0; i--)//补前面的0
        time[i] = '0';
}

void insert(tire *op,char *time )
{
    int len = 32 + 2;
    tire *p = op, *q;
    for (int i = 0; i < len; i++)
    {
        int id = time[i] - '0';
        if (p->next[id] == NULL)
        {
            q = (tire*)malloc(sizeof(tire));
            for (int i = 0; i < LEN; i++)
                q->next[i] = NULL;
            p->next[id] = q;
        }
        p = p->next[id];
    }
}

ll search(tire *op, char *time)
{
    int len = 32 + 2;
    tire *p = op;
    ll k = 2, sum = 0;
    k <<= 32;
    for (int i = 0; i < len; i++)
    {
        int id = time[i] - '0';
        if (p->next[id] == NULL)
            p = p->next[id ^ 1];
        else
        {
            p = p->next[id];
            sum += k;
        }
        k /= 2;
    }
    return sum;
}

int main()
{
    int T, n, m;
    int icase = 0;
    char time[50];
    scanf("%d", &T);
    while (T--)
    {
        tire *op = (tire*)malloc(sizeof(tire));
        for (int i = 0; i < LEN; i++)
            op->next[i] = NULL;
        scanf("%d %d", &n, &m);
        while (n--)
        {
            ll mid = 0;
            scanf("%d", &mid);
            get_char(time, mid);
            insert(op, time);
        }
        printf("Case #%d:
", ++icase);
        while (m--)
        {
            ll mm = 0;
            scanf("%d", &mm);
            get_char(time,mm);
            for (int i = 0; i < 32 + 2; i++)
                if (time[i] == '1')
                    time[i] = '0';
                else
                    time[i] = '1';
            printf("%lld
", search(op, time) ^ mm);
        }
    }
    return 0;
}
View Code
 
原文地址:https://www.cnblogs.com/7750-13/p/7354835.html