HDU

来源:互联网 发布:一键越狱软件 编辑:程序博客网 时间:2024/06/15 22:30

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

23 23 4 5154 14 6 5 63

Sample Output

Case #1:43Case #2:4

1.建一个二叉字典树;
2.⭐⭐⭐从31位开始,由高位往低位建!

#include<cstdio>#include<cmath>#include<cstring>#include<iostream>#include<algorithm>#define Tcases int T;scanf("%d",&T);while(T--)using namespace std;typedef long long LL;struct Node {    int val;    Node* next[2];    Node() {        val = 0;        next[0] = next[1] = NULL;    }}root;void build_Trie(int x) {    Node *p = &root;    int nxt;    for (int i = 31; i >= 0; i--) {        if ((x&(1 << i)) == 0)            nxt = 0;        else             nxt = 1;        if (p->next[nxt] == NULL)            p->next[nxt] = new Node();        p = p->next[nxt];    }    p->val = x;}int find_Trie(int x) {    int nxt;    Node* p = &root;    for (int i = 31; i >= 0; i--) {        if ((x&(1 << i)) == 0)//注意从高位往低位建的方法            nxt = 1;        else            nxt = 0;        if (p->next[nxt] != NULL)            p = p->next[nxt];        else if (p->next[!nxt] != NULL)            p = p->next[!nxt];        else return p->val;    }    return p->val;}int main(){#ifdef _DEBUG    freopen("debug.in", "r", stdin);#endif     int kase = 0;    Tcases{        root.next[0] = root.next[1] = NULL;        int n,m,temp;        scanf("%d%d",&n,&m);        for (int i = 0; i < n; i++) {            scanf("%d", &temp);            build_Trie(temp);        }        printf("Case #%d:\n", ++kase);        for (int i = 0; i < m; i++) {            scanf("%d", &temp);            printf("%d\n",find_Trie(temp));        }    }    return 0;}
原创粉丝点击