Xor Sum
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 132768/132768 K (Java/Others)Total Submission(s): 3313 Accepted Submission(s): 1435
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
Sample Output
Case #1:
4
3
Case #2:
4
Source
Recommend
#include<bits/stdc++.h>
typedef long long ll;
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
ll bin[35];
//int val[100005];
ll ans ;
//01字典樹
struct trie{
int cnt;
int ch[4000005][2];//zis = 30 * MAXN
void init()
{
memset(ch,0,sizeof(ch));
cnt = 0;
}
void insert(int x)
{
ll now=0;
for(int i=30;i>=0;i--)
{
ll t=x&bin[i];t>>=i;
if(!ch[now][t]) ch[now][t]=++cnt;
now=ch[now][t];
}
}
void query(int x)
{
ll tmp=0,now=0;//當前爲x 尋找另一個y 使得x^y最大
for(int i=30;i>=0;i--)
{
ll t=x&bin[i];t>>=i;
if(ch[now][t^1])
{
now=ch[now][t^1];
if(t^1)
tmp+=bin[i];
}
else
{
now=ch[now][t];
if(t)
tmp+=bin[i];
}
}
ans=tmp;
}
}trie;
int T;
ll t;
int n,m;
int main()
{
// freopen("data.txt","r",stdin);
ios_base::sync_with_stdio(false);
bin[0]=1;for(int i=1;i<=33;i++)bin[i]=bin[i-1]<<1;
cin >> T;
for(int cas=1;cas<=T;cas++)
{
cout <<"Case #"<<cas<<":"<<endl;
trie.init();
cin >> n>>m;
for(int i=1;i<=n;i++)
{
cin >> t;
trie.insert(t);
}
for(int i=1;i<=m;i++)
{
cin >> t;
trie.query(t);
cout << ans<<endl;
}
}
return 0;
}