A - 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
題意:不說了
思路:把數存在字典樹裏 查找異或值
注意: 數組大小
代碼:
#include<set>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#define mem(a,b) memset(a,b,sizeof(a))
using namespace std;
const int maxn=1e5;
int trie[5000000][2];
int vis[5000000];
int tot,rt;
int er[40];
void Build_trie(int *er,int f)
{
rt=0;
for(int j=35; j>=0; j--)
{
int y=er[j];
if(!trie[rt][y])
trie[rt][y]=++tot;
rt=trie[rt][y];
}
vis[rt]=f;
}
int Find_trie(int *er)
{
rt=0;
for(int j=35; j>=0; j--)
{
int y=!er[j];
if(!trie[rt][y])
{
y=!y;
}
rt=trie[rt][y];
}
return vis[rt];
}
int main()
{
int ca,cas=1;
scanf("%d",&ca);
while(ca--)
{
tot=0;
mem(trie,0);
mem(vis,0);
int n,m,x,i,f;
scanf("%d%d",&n,&m);
while(n--)
{
i=0;
mem(er,0);
scanf("%d",&x);
f=x;
while(x)
{
er[i]=x%2;
x/=2;
i++;
}
Build_trie(er,f);
}
printf("Case #%d:\n",cas++);
while(m--)
{
i=0;
scanf("%d",&x);
memset(er,0,sizeof(er));
while(x)
{
er[i]=x%2; //不能是(x+1)%2; 會WR;
x/=2;
i++;
}
printf("%d\n",Find_trie(er));
}
}
return 0;
}