01字典树的实现可以看成是把一个数的二进制字符化后插入到一颗一般的字典树中
比如在01字典树种插入3时 相当于在字典树中插入00 …..00011(一共33为,这个根据具体实现不同)
查找最大异或值的时候我们是从最高位 向下贪心查找 贪心策略为:当前查找第k位 二进制数位IDX 如果存在IDX ^ 1的节点 我们就进入这个节点 否则进入IDX节点
贪心策略的证明: 如果这时我们进入了第K位为IDX 的节点 那么 第k位为IDX ^ 1 的节点组成的数 异或X一定更大最后关于01字典树的使用:
不用关心代码内部是如何实现的
只将01字典树看做是一个数集 我们可以在这个集合中查找和X异或最大的元素应用:
经常有区间异或和的题目:比如求[l,r]的异或和
由X xor X = 0 ; 0 xor Y = Y;所有【l,r】 = 【1,r】 XOR 【1,l - 1】
这样在一颗加入了r 前的所有前缀异或和的01字典树上查找【1,r】就能得到以r为右边界的最大异或和
1. 01字典树是一棵最多 32层的二叉树,其每个节点的两条边分别表示二进制的某一位的值为 0 还是为 1. 将某个路径上边的值连起来就得到一个二进制串。
2.节点个数为 1 的层(最高层)节点的边对应着二进制串的最高位。
3.以上代码中,ch[i] 表示一个节点,ch[i][0] 和 ch[i][1] 表示节点的两条边指向的节点,val[i] 表示节点的值。
4.每个节点主要有 4个属性:节点值、节点编号、两条边指向的下一节点的编号。
5.节点值 val为 0时表示到当前节点为止不能形成一个数,否则 val[i]=数值。
6.可通过贪心的策略来寻找与 x异或结果最大的数,即优先找和 x二进制的未处理的最高位值不同的边对应的点,这样保证结果最大。
#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
#include<vector>
#include<cmath>
#include<string>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
const int maxn=100010;
int ch[32*maxn][2];//字典树节点
int val[32*maxn];//每个节点对应的数值
int nodecnt;//总结点数
//初始化01字典树
void init(){
nodecnt=1;
ch[0][1]=ch[0][0]=0;
}
//插入01字典树
void tire(int x){
int cnt=0;
for(int i=31;i>=0;i--){
int v=(x>>i)&1;
if(!ch[cnt][v]){//如果此指针指向空
ch[nodecnt][0]=ch[nodecnt][1]=0;
val[nodecnt]=0;
ch[cnt][v]=nodecnt++;
}
cnt=ch[cnt][v];
}
val[cnt]=x;
return ;
}
int find(int x){
int cnt=0;
for(int i=31;i>=0;i--){
int v=(x>>i)&1;
//利用贪心策略,优先寻找和当前位不同的数
if(ch[cnt][v^1])cnt=ch[cnt][v^1];
else cnt=ch[cnt][v];
}
return val[cnt];
}
int main(){
int t,n,m,num,example=1;
scanf("%d",&t);
while(t--){
printf("Case #%d:\n",example++);
scanf("%d %d",&n,&m);
init();
for(int i=0;i<n;i++){
scanf("%d",&num);
tire(num);
}
while(m--){
scanf("%d",&num);
printf("%d\n",find(num));
}
}
return 0;
}
// /\ | / |**、
// / \ | / | \
// / \ |/ | / _____ ____ | /
// /------\ |\ |__/ / \ \ /\ / / \ | /
// / \ | \ | / \ \ / \ / /______\ |/
// / \ | \ | \ / \ / \ / \ |
// / \ | \ | \_____/ \/ \/ \_____ |
/**
* ┏┓ ┏┓
* ┏┛┗━━━━━━━┛┗━━━┓
* ┃ ┃
* ┃ ━ ┃
* ┃ > < ┃
* ┃ ┃
* ┃... ⌒ ... ┃
* ┃ ┃
* ┗━┓ ┏━┛
* ┃ ┃ Code is far away from bug with the animal protecting
* ┃ ┃ 神兽保佑,代码无bug
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*/
// warm heart, wagging tail,and a smile just for you!
//
// _ooOoo_
// o8888888o
// 88" . "88
// (| -_- |)
// O\ = /O
// ____/`---'\____
// .' \| |// `.
// / \||| : |||// \
// / _||||| -:- |||||- \
// | | \\ - /// | |
// | \_| ''\---/'' | |
// \ .-\__ `-` ___/-. /
// ___`. .' /--.--\ `. . __
// ."" '< `.___\_<|>_/___.' >'"".
// | | : `- \`.;`\ _ /`;.`/ - ` : | |
// \ \ `-. \_ __\ /__ _/ .-` / /
// ======`-.____`-.___\_____/___.-`____.-'======
// `=---='
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//