# bzoj 1901(主席树套树状数组)

## 1901: Zju2112 Dynamic Rankings

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 6275  Solved: 2604
[Submit][Status][Discuss]

5 3
3 2 1 4 7
Q 1 4 3
C 2 6
Q 2 5 3

3
6

## HINT

20%的数据中，m,n≤100; 40%的数据中，m,n≤1000; 100%的数据中，m,n≤10000。

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
using namespace std;
int n,m,size,A,B,len;
struct ss
{
int zhi,dui;
} q[20005];
int a[20001];
int sum[2200001],r[2200001],l[2200001];
int oc[30],og[30];
char c[20001][2];
int qi[20001][3];
int hash[20001];
int root[10001];

{
char y;int x=0,f=1; y=getchar();
while (y<'0' || y>'9') {if (y=='-') f=-1; y=getchar();}
while (y>='0' && y<='9') {x=x*10+int(y)-48; y=getchar();}
return x*f;
}

bool cmp(ss x,ss y)
{
return x.zhi<y.zhi;
}

void build(int x,int lg,int rg,int v,int &y,int flag)
{
++size; y=size;
sum[y]=sum[x]+flag;
int mid=(lg+rg)/2;
if (lg==rg) return;
l[y]=l[x]; r[y]=r[x];
if (v<=mid)
{
build(l[x],lg,mid,v,l[y],flag);
}else
build(r[x],mid+1,rg,v,r[y],flag);
}

int query(int lg,int rg,int k)
{
if (lg==rg) return lg;
int suml=0; int sumr=0;
for (int i=1;i<=A;++i) suml+=sum[l[oc[i]]];
for (int i=1;i<=B;++i) sumr+=sum[l[og[i]]];
int mid=(lg+rg)/2;
if (sumr-suml>=k)
{
for (int i=1;i<=A;++i) oc[i]=l[oc[i]];
for (int i=1;i<=B;++i) og[i]=l[og[i]];
return query(lg,mid,k);
}else
{
for (int i=1;i<=A;++i) oc[i]=r[oc[i]];
for (int i=1;i<=B;++i) og[i]=r[og[i]];
return query(mid+1,rg,k-(sumr-suml));
}
}

int main()
{
for (int i=1;i<=n;++i)
{
++tcc;
q[tcc].zhi=a[i];  q[tcc].dui=i;
}
for (int i=1;i<=m;++i)
{
scanf("%s",c[i]);
{
++tcc; q[tcc].zhi=qi[i][1]; q[tcc].dui=n+i;
}
}
sort(q+1,q+tcc+1,cmp); len=0;
for (int i=1;i<=tcc;++i)
{
if (q[i].zhi!=q[i-1].zhi || i==1)
{
++len;
hash[len]=q[i].zhi;
}
if (q[i].dui<=n)
{
a[q[i].dui]=len;
}else
{
qi[q[i].dui-n][1]=len;
}
}
for (int i=1;i<=n;++i)
{
int now=i;
while (now<=n)
{
build(root[now],1,len,a[i],root[now],1);
now+=now&-now;
}
}
for (int i=1;i<=m;++i)
{
if (c[i][0]=='Q')
{
--qi[i][0];
A=0; B=0; int u1=qi[i][0]; int u2=qi[i][1];
while (u1>0) { ++A; oc[A]=root[u1]; u1-=u1&-u1;}
while (u2>0) { ++B; og[B]=root[u2]; u2-=u2&-u2;}
printf("%d\n",hash[query(1,len,qi[i][2])]);
}else
{
int now=qi[i][0];
while (now<=n)
{
build(root[now],1,len,a[qi[i][0]],root[now],-1);
now+=now&-now;
}
a[qi[i][0]]=qi[i][1];
now=qi[i][0];
{
while(now<=n)
{
build(root[now],1,len,qi[i][1],root[now],1);
now+=now&-now;
}
}
}
}
}

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客