Xor Sum
HDU - 4825
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 3Sample Output
Case #1: 4 3 Case #2: 4
01字典树模板:
01字典树问题,它是用来解决xor的有力武器,通常是给你一个数组,问你一段连续的异或和最大是多少,正常思路贪心dp啥的都会一头雾水,但是用01字典树就能很快的解决,实现起来也十分方便。
将要插入的数的二进制位倒着建树(为什么?因为异或时高位尽量大,结果才尽量大),即高位在深度低的节点上
贴一个01字典树的普遍模版
- #define Memset(x, a) memset(x, a, sizeof(x))
- typedef long long ll;
- const int maxn = 100000 + 5;//集合中的数字个数
- int ch[32*maxn][2]; //节点的边信息
- ll val[32*maxn]; //节点存储的值
- int sz; //树中当前节点个数
- void init(){
- Memset(ch[0],0); //树清空
- sz=1;
- }
- void _insert(ll a){//在字典树中插入 a
- //和一般字典树的操作相同 将X的二进制插入到字典树中
- int u=0;
- for(int i=32;i>=0;i--){
- int c=((a>>i)&1);
- if(!ch[u][c]){
- Memset(ch[sz],0);
- val[sz]=0;
- ch[u][c]=sz++;
- }
- u=ch[u][c];
- }
- val[u]=a; //最后的节点插入value
- }
- ll query(ll a){ //在字典树中查找和a异或的值最大的元素b 返回b的值
- int u=0;
- for(int i=32;i>=0;i--){
- int c=((a>>i)&1);
- if(ch[u][c^1]) u=ch[u][c^1];//c=0,b=c^1=1,b^c=1;c=1,b=c^1=0,b^c=1;
- else u=ch[u][c];
- }
- return val[u];
- }
ac code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
typedef long long ll;
const int maxn = 1e5+5;
int tree[32*maxn][2];
ll val[32*maxn];//节点储存的值
int sz;//树中当前节点个数
void init(){
memset(tree[0],0,sizeof(tree[0]));
sz = 1;
}
void Insert(ll a){
int u = 0;
for(int i = 32; i >= 0; i--){
int c = ((a>>i)&1);//确定最高位的二进制码
if(!tree[u][c]){//如果这个位置是个空,则将这个位置标上节点号,并创建它的子节点
memset(tree[sz],0,sizeof(tree[sz]));
val[sz] = 0;
tree[u][c] = sz++;//存下这个位置的节点号
}
u = tree[u][c];//转到下一节点
}
val[u] = a;//最后存完后在最后节点存上这个数值
}
ll query(ll a){
int u = 0;
for(int i = 32; i >= 0; i--){
int c = ((a>>i)&1);
if(tree[u][c^1]) u = tree[u][c^1];//c = 0,c^1 = 1;c = 1,c^1 = 0;尽可能在高位找使它异或为1的
else u = tree[u][c];
}
return val[u];
}
int main(){
int t,n,m;
scanf("%d",&t);
for(int cas = 1; cas <= t; cas++){
init();
scanf("%d%d",&n,&m);
ll a;
for(int i = 0; i < n; i++){
scanf("%lld",&a);
Insert(a);
}
printf("Case #%d:\n",cas);
for(int i = 0; i < m; i++){
scanf("%lld",&a);
printf("%lld\n",query(a));
}
}
return 0;
}