
Xor Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 132768/132768 K (Java/Others)
Total Submission(s): 3647 Accepted Submission(s): 1595
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。
输入的第一行是一个整数T(T < 10),表示共有T组数据。
每组数据的第一行输入两个正整数N,M(<1=N,M<=100000),接下来一行,包含N个正整数,代表 Zeus 的获得的集合,之后M行,每行一个正整数S,代表 Prometheus 询问的正整数。所有正整数均不超过2^32。
Output
对于每组数据,首先需要输出单独一行”Case #?:”,其中问号处应填入当前的数据组数,组数从1开始计算。
对于每个询问,输出一个正整数K,使得K与S异或值最大。
对于每个询问,输出一个正整数K,使得K与S异或值最大。
Sample Input
2
3 2
3 4 5
1
5
4 1
4 6 5 6
3
3 2
3 4 5
1
5
4 1
4 6 5 6
3
Sample Output
Case #1:
4
3
Case #2:
4
4
3
Case #2:
4
分析
要求求出原集合中与所给的数异或值最大的数。
建立一颗trie树,左边是0,右边是1。将所有数放到trie树中。
那么,对于给定的数x,将x二进制分解,在trie中从高位往低位走,每一位最好是和x不同(异或:不同为1,相同为0)。
code
#include<cstdio>
#include<algorithm>
#include<cstring> using namespace std;
const int N = ; inline char nc() {
static char buf[],*p1=buf,*p2=buf;
return p1==p2&&(p2=(p1=buf)+fread(buf,,,stdin),p1==p2)?EOF:*p1++;
}
inline int read() {
int x = ,f = ;char ch = nc();
for (; ch<''||ch>''; ch=nc()) if(x=='-')f=-;
for (; ch>=''&&ch<=''; ch=nc()) x=x*+ch-'';
return x * f;
}
struct Trie{
int val[N],ch[N][];
int cnt;
void init() {
memset(ch,,sizeof(ch));
memset(val,,sizeof(val));
cnt = ;
}
void Insert(int x) {
int u = ;
for (int i=; i>=; --i) {
int c = (x&(<<i)) > ;
if (!ch[u][c]) ch[u][c] = ++cnt;
u = ch[u][c];
}
val[u] = x;
}
int Query(int x) {
int u = ;
for (int i=; i>=; --i) {
int c = (x&(<<i))>;
if (ch[u][!c]) u = ch[u][!c];
else if(ch[u][c]) u = ch[u][c]; //
}
return val[u];
}
}t; int main () {
int T = read();
for (int Case=; Case<=T; ++Case) {
t.init();
int n = read(),m = read();
for (int i=; i<=n; ++i) {
int a = read();
t.Insert(a);
}
printf("Case #%d:\n",Case);
while (m--) {
int a = read();
printf("%d\n",t.Query(a));
}
}
return ;
}