HDU4825 Xor Sum —— Trie树

题目链接:https://vjudge.net/problem/HDU-4825

Xor Sum

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


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
 
Recommend
liuyiding

题解:

将所有数按二进制从高位到低位插入到Trie树中,然后再枚举每一个数,去Trie中反向匹配即可。

代码如下:

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <algorithm>
 5 #include <vector>
 6 #include <cmath>
 7 #include <queue>
 8 #include <stack>
 9 #include <map>
10 #include <string>
11 #include <set>
12 using namespace std;
13 typedef long long LL;
14 const int INF = 2e9;
15 const LL LNF = 9e18;
16 const int MOD = 1e9+7;
17 const int MAXN = 1e5+10;
18 
19 struct Trie
20 {
21     int next[33*MAXN][2];
22     int root, L = 0;
23     int newnode()
24     {
25         next[L][0] = next[L][1] = -1;
26         L++;
27         return L-1;
28     }
29     void init()
30     {
31         L = 0;
32         root = newnode();
33     }
34     void insert(LL val)
35     {
36         int tmp = root, way;
37         for(int i = 32; i>=0; i--)
38         {
39             way = (val>>i)&1;
40             if(next[tmp][way]==-1) next[tmp][way] = newnode();
41             tmp = next[tmp][way];
42         }
43     }
44     LL query(LL val)
45     {
46         LL ret = 0;
47         int tmp = root, way;
48         for(int i = 32; i>=0; i--)
49         {
50             ret <<= 1;
51             way = (val>>i)&1;
52             if(next[tmp][!way]!=-1) //如果另一方向存在,则走另一方向
53                 ret ^= !way, tmp = next[tmp][!way];
54             else    //否则,顺着走
55                 ret ^= way, tmp = next[tmp][way];
56         }
57         return ret;
58     }
59 };
60 Trie T;
61 
62 int main()
63 {
64     int n, m, TT;
65     scanf("%d",&TT);
66     for(int kase = 1; kase<=TT; kase++)
67     {
68         scanf("%d%d",&n,&m);
69         T.init();
70         for(int i = 1; i<=n; i++)
71         {
72             LL val;
73             scanf("%lld",&val);
74             T.insert(val);
75         }
76 
77         printf("Case #%d:
",kase);
78         while(m--)
79         {
80             LL val;
81             scanf("%lld",&val);
82             printf("%lld
", T.query(val));
83         }
84     }
85 }
View Code
原文地址:https://www.cnblogs.com/DOLFAMINGO/p/8727860.html