# [BZOJ1901]Zju2112 Dynamic Rankings（树状数组套主席树）

## 代码

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,m,a[10010],h[20010],tot,s[10010],ul[10010],ur[10010],cl,cr,cnt;
struct query{
int type,l,r,v;
}q[10010];
struct segtree{
int l,r,val;
}t[2000010];
int lowbit(int i){return i&(-i);}
void insert(int &i,int l,int r,int x,int v){
if (i==0) i=++cnt;
t[i].val+=v;
if (l==r) return;
int mid=(l+r)>>1;
if (x<=mid) insert(t[i].l,l,mid,x,v);
else insert(t[i].r,mid+1,r,x,v);
}
while (i<=n){
insert(s[i],1,tot,x,v);
i+=lowbit(i);
}
}
int getpos(int L,int R){
cl=cr=0;
while (L!=0){ul[++cl]=s[L];L-=lowbit(L);}
while (R!=0){ur[++cr]=s[R];R-=lowbit(R);}
}
int getsum(int n,int *s){
int sum=0;
for (int i=1;i<=n;i++)
sum+=t[t[s[i]].l].val;
return sum;
}
if (l==r) return l;
int val,mid=(l+r)>>1;
val=getsum(cr,ur)-getsum(cl,ul);
if (val>=k){
for (int i=1;i<=cl;i++) ul[i]=t[ul[i]].l;
for (int i=1;i<=cr;i++) ur[i]=t[ur[i]].l;
}else{
for (int i=1;i<=cl;i++) ul[i]=t[ul[i]].r;
for (int i=1;i<=cr;i++) ur[i]=t[ur[i]].r;
}
}
int main()
{
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++){
scanf("%d",&a[i]);
h[++tot]=a[i];
}
for (int i=1;i<=m;i++){
char c=getchar();
while (c!='Q'&&c!='C') c=getchar();
if (c=='Q'){
scanf("%d%d%d",&q[i].l,&q[i].r,&q[i].v);
q[i].type=1;
}else{
scanf("%d%d",&q[i].l,&q[i].v);
h[++tot]=q[i].v;q[i].type=2;
}
}
sort(h+1,h+tot+1);
tot=unique(h+1,h+tot+1)-h-1;
for (int i=1;i<=n;i++)
a[i]=lower_bound(h+1,h+tot+1,a[i])-h;
for (int i=1;i<=m;i++)
if (q[i].type==1){
getpos(q[i].l-1,q[i].r);
printf("%d\n",h[ans]);
}else{
a[q[i].l]=q[i].v;
a[q[i].l]=lower_bound(h+1,h+tot+1,a[q[i].l])-h;