链接:https://www.luogu.org/problemnew/show/P2617
思路:
如果直接在主席树上修改的话,每次修改都会对后面所有的树造成影响,一次修改的复杂度就会变成 : n*logn,我们套上树状数组维护,每次就最多只用更新logn棵树,复杂度是:logn*logn,是可以接受的;
代码参考hzwer: http://hzwer.com/2835.html
实现代码;
#include<bits/stdc++.h>
using namespace std;
const int M = 2e5+;
int v[M],num[M*],has[M*];
int op[M],A[M],B[M],K[M],rt[M];
int sum[M*],ls[M*],rs[M*];
int L[],R[],a,b,tot,idx,k; int lowbit(int x){
return x&(-x);
} int find(int x){
int l = ,r = tot;
while(l <= r){
int mid = (l + r) >> ;
if(has[mid] < x) l = mid + ;
else r = mid - ;
}
return l;
} void update(int old,int &k,int p,int c,int l,int r){
k = ++idx;
ls[k] = ls[old],rs[k] = rs[old];
sum[k] = sum[old] + c;
if(l == r) return ;
int mid = (l + r) >> ;
if(p <= mid) update(ls[old],ls[k],p,c,l,mid);
else update(rs[old],rs[k],p,c,mid+,r);
} int query(int l,int r,int k){
if(l == r) return l;
int suml = ,sumr = ;
for(int i = ;i <= a;i ++) suml += sum[ls[L[i]]];
for(int i = ;i <= b;i ++) sumr += sum[ls[R[i]]];
int mid = (l + r) >> ;
if(sumr - suml >= k){
for(int i = ;i <= a;i ++) L[i] = ls[L[i]];
for(int i = ;i <= b;i ++) R[i] = ls[R[i]];
return query(l,mid,k);
}
else {
for(int i = ;i <= a;i ++) L[i] = rs[L[i]];
for(int i = ;i <= b;i ++) R[i] = rs[R[i]];
return query(mid+,r,k-(sumr-suml));
}
} int main()
{
int n,m,cnt = ;
scanf("%d%d",&n,&m);
for(int i = ;i <= n;i ++){
scanf("%d",&v[i]);
num[++cnt] = v[i];
}
char s[];
for(int i = ;i <= m;i ++){
scanf("%s",s);
scanf("%d%d",&A[i],&B[i]);
if(s[]=='Q') scanf("%d",&K[i]),op[i] = ;
else num[++cnt] = B[i];
}
sort(num+,num+cnt+);
has[++tot] = num[];
for(int i = ;i <= cnt;i ++){
if(num[i] != num[i-])
has[++tot] = num[i];
}
for(int i = ;i <= n;i ++){
int k = find(v[i]);
for(int j = i;j <= n;j += lowbit(j))
update(rt[j],rt[j],k,,,tot);
}
for(int i = ;i <= m;i ++){
if(op[i]){
a = ; b = ; A[i]--;
for(int j = A[i];j > ;j -= lowbit(j))
L[++a] = rt[j];
for(int j = B[i];j > ;j -= lowbit(j))
R[++b] = rt[j];
printf("%d\n",has[query(,tot,K[i])]);
}
else{
int k = find(v[A[i]]);
for(int j = A[i];j <= n;j += lowbit(j))
update(rt[j],rt[j],k,-,,tot);
v[A[i]] = B[i];
k = find(B[i]);
for(int j = A[i];j <= n;j += lowbit(j))
update(rt[j],rt[j],k,,,tot);
}
}
return ;
}