学到了一种新的数据结构——字典树
貌似用链表存是最好的办法
容易证明查询的时候尽量走与p不同的路能是p^c最大
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
struct T{
int c;
T *left,*right;
};
void insert(int c,T* root,int dit){
if(dit==-1){
root->c=c;
return ;
}
if((c&(1<<dit))==0){
if(root->left==NULL){
T *child=(T*)malloc(sizeof(T));
child->right=child->left=NULL;
child->c=-1;
root->left=child;
insert(c,child,dit-1);
}
else
insert(c,root->left,dit-1);
}
else{
if(root->right==NULL){
T *child=(T*)malloc(sizeof(T));
child->left=child->right=NULL;
child->c=-1;
root->right=child;
insert(c,child,dit-1);
}
else
insert(c,root->right,dit-1);
}
}
void dfs(T* root){
// cout<<(root->c)<<" "<<(root->left)<<root->right<<endl;
if(root->left!=NULL)
dfs(root->left);
if(root->right!=NULL)
dfs(root->right);
}
int query(int p,T* root,int dit){
//cout<<root<<" "<<dit<<" "<<root->c<<endl;
if(dit==-1){
return root->c;
}
if((p&(1<<dit))==0){
if(root->right==NULL){
return query(p,root->left,dit-1);
}
else
return query(p,root->right,dit-1);
}
else{
if(root->left==NULL){
return query(p,root->right,dit-1);
}
else
return query(p,root->left,dit-1);
}
}
int main(){
int n,m,type,c,p;
cin>>n;
T *root=(T*)malloc(sizeof(T));
root->left=root->right=NULL;
root->c=-1;
while(n--){
cin>>c;
insert(c,root,19);
}
// dfs(root);
cin>>m;
while(m--){
cin>>type;
if(type==0){
cin>>c;
insert(c,root,19);
}
else{
cin>>p;
cout<<query(p,root,19)<<endl;
}
}
return 0;
}