【带修改的主席树】BZOJ1901-Dynamic Rankings

稍后整理笔记。这题数据范围好像有点问题?

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<vector>
#include<algorithm>
#define lson l,m
#define rson m+1,r
using namespace std;
const int MAXN=+;
int n,q,tot,m,d;
struct node
{
int l,r,k,Q;
}op[MAXN];
int a[MAXN<<],hash[MAXN<<],T[MAXN<<],S[MAXN<<],use[MAXN<<];
int L[MAXN<<],R[MAXN<<],sum[MAXN<<]; int lowbit(int x)
{
return (x&(-x));
} int build(int l,int r)
{
int rt=++tot;
sum[rt]=;
if (l!=r)
{
int m=(l+r)>>;
L[rt]=build(lson);
R[rt]=build(rson);
}
return rt;
} int update(int pre,int l,int r,int x,int op)
{
int rt=++tot;
L[rt]=L[pre],R[rt]=R[pre],sum[rt]=sum[pre]+op;
if (l<r)
{
int m=(l+r)>>;
if (x<=m) L[rt]=update(L[pre],lson,x,op);
else R[rt]=update(R[pre],rson,x,op);
}
return rt;
} int Sum(int x)
{
int ret=;
while (x>)
{
ret+=sum[L[use[x]]];
x-=lowbit(x);
}
return ret;
} int query(int Sl,int Sr,int Tl,int Tr,int l,int r,int k)
{
if (l==r) return l;
int m=(l+r)>>;
int tmp=Sum(Sr)-Sum(Sl)+sum[L[Tr]]-sum[L[Tl]];
if (tmp>=k)
{
for (int i=Sl;i;i-=lowbit(i)) use[i]=L[use[i]];
for (int i=Sr;i;i-=lowbit(i)) use[i]=L[use[i]];
return query(Sl,Sr,L[Tl],L[Tr],lson,k);
}
else
{
for (int i=Sl;i;i-=lowbit(i)) use[i]=R[use[i]];
for (int i=Sr;i;i-=lowbit(i)) use[i]=R[use[i]];
return query(Sl,Sr,R[Tl],R[Tr],rson,k-tmp);
}
} void modify(int x,int p,int delta)
{
while (x<=n)
{
S[x]=update(S[x],,d,p,delta);
x+=lowbit(x);
}
} void init()
{
tot=;
m=;
d=;
scanf("%d%d",&n,&q);
for (int i=;i<=n;i++) scanf("%d",&a[i]),hash[++m]=a[i];
for (int i=;i<q;i++)
{
char s[];
scanf("%s",s);
if (s[]=='Q') scanf("%d%d%d",&op[i].l,&op[i].r,&op[i].k),op[i].Q=;
else
{
scanf("%d%d",&op[i].l,&op[i].r);
op[i].Q=;
hash[++m]=op[i].r;
}
}
/*因为修改后的数可能不在初始几个数的范围内,故要先输入完查询*/ sort(hash+,hash+m+);
d=unique(hash+,hash++m)-hash-; T[]=build(,d);//T表示每一步T树的树根
for (int i=;i<=n;i++)
{
int x=lower_bound(hash+,hash+d+,a[i])-hash;
T[i]=update(T[i-],,d,x,);
} for (int i=;i<=n;i++) S[i]=T[];
} void solve()
{ for (int i=;i<q;i++)
{
if (op[i].Q)
{
for (int j=op[i].l-;j;j-=lowbit(j)) use[j]=S[j];
for (int j=op[i].r;j;j-=lowbit(j)) use[j]=S[j];
int ans=query(op[i].l-,op[i].r,T[op[i].l-],T[op[i].r],,d,op[i].k);
printf("%d\n",hash[ans]);
}
else
{
int x=lower_bound(hash+,hash+d+,a[op[i].l])-hash;
int y=lower_bound(hash+,hash+d+,op[i].r)-hash;
modify(op[i].l,x,-);
modify(op[i].l,y,);
a[op[i].l] =op[i].r;
}
}
} int main()
{
init();
solve();
return ;
}
上一篇:jquery js解析函数、函数直接调用


下一篇:jquery and js 判断一个元素是否存在