# 【洛谷5795】[THUSC2015] 异或运算（可持久化Trie）

### 优化做法

$XZY$神仙的指导下，我知道了该怎么把这个做法优化为一个$log$

### 代码

#include<bits/stdc++.h>
#define Tp template<typename Ty>
#define Ts template<typename Ty,typename... Ar>
#define Reg register
#define RI Reg int
#define Con const
#define CI Con int&
#define I inline
#define W while
#define N 1000
#define M 300000
using namespace std;
int n,m,a[N+5],b[M+5];
class FastIO
{
private:
#define FS 100000
#define tn (x<<3)+(x<<1)
#define D isdigit(c=tc())
char c,*A,*B,FI[FS];
public:
I FastIO() {A=B=FI;}
Tp I void read(Ty& x) {x=0;W(!D);W(x=tn+(c&15),D);}
}F;
class ChairmanTrie
{
private:
int T;struct node {int Sz;node* S[2];I node() {Sz=0,S[0]=S[1]=NULL;}}*Rt[M+5],*l[N+5],*r[N+5];
#define Sz(x) (x==NULL?0:x->Sz)
#define S(x,d) (x==NULL?NULL:x->S[d])
I void Ins(node*& rt,node* lst,CI x,CI d)//插入
{
rt=new node,rt->Sz=Sz(lst),rt->S[0]=S(lst,0),rt->S[1]=S(lst,1);
if(++rt->Sz,!~d) return;int t=(x>>d)&1;Ins(rt->S[t],S(lst,t),x,d-1);
}
I int Qry(CI s,CI t,CI k,CI d)//询问
{
if(!~d) return 0;RI i,tot=0;
for(i=s;i<=t;++i) tot+=Sz(S(r[i],(a[i]>>d)&1^1))-Sz(S(l[i],(a[i]>>d)&1^1));//统计能有的1的个数
if(tot>=k)//如果个数大于等于k，说明这一位能填1
{
for(i=s;i<=t;++i) l[i]=S(l[i],(a[i]>>d)&1^1),r[i]=S(r[i],(a[i]>>d)&1^1);
return Qry(s,t,k,d-1)|(1<<d);
}
else//否则填0
{
for(i=s;i<=t;++i) l[i]=S(l[i],(a[i]>>d)&1),r[i]=S(r[i],(a[i]>>d)&1);
return Qry(s,t,k-tot,d-1);
}
}
public:
I ChairmanTrie() {for(RI i=1;i<=N;++i) Rt[i]=NULL;}
I void Ins(CI v,CI v_,CI x) {Ins(Rt[v],Rt[v_],x,30);}
I int Qry(CI vl,CI vr,CI s,CI t,CI k)
{
for(RI i=s;i<=t;++i) l[i]=Rt[vl-1],r[i]=Rt[vr];return Qry(s,t,k,30);//初始化每一行所对应的节点为根节点
}
}T;
int main()
{