# bzoj 1901 && P2617 Dynamic Ranking

## 输入输出格式

• Q i j k （i,j,k是数字，1≤i≤j≤n, 1≤k≤j-i+1）表示询问指令，询问a[i]，a[i+1]……a[j]中第k小的数。

• C i t (1≤i≤n，0≤t≤10^9)表示把a[i]改变成为t。

## 输入输出样例

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

3
6


## 说明

20%的数据中，m,n≤100;

40%的数据中，m,n≤1000;

100%的数据中，m,n≤10000。

#include<cmath>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<iostream>
#include<algorithm>
#define For(i,a,b) for(i=(a);i<=(b);++i)
#define rep(i,a,b) for(i=(a);i>=(b);--i)
#define ll long long
#define inf 999999999
#define mm(a,b) memset(a,b,sizeof(a))
using namespace std;
int sum = 0,fg = 1;char c = getchar();
while(c < '0' || c > '9'){if(c =='-')fg = -1;c = getchar();}
while(c >='0' && c <='9')sum = sum*10 + c-'0',c = getchar();
return sum*fg;
}
int lowbit(int x){return x & -x;}
const int maxn = 6000010;
const int maxm = 10010;
int a[maxm] ,ls[maxm*2] ,cnt ,A[maxm] ,B[maxm] ,K[maxm] ,tree[maxm] ,node;
int sum[maxn] ,l[maxn] ,r[maxn] ,lcnt, rcnt, lsl[maxm], lsr[maxm] ,n ,m;
char ss[5] ;
void build(int s , int e , int x , int &y , int pos , int type){//普通的主席树insert
y = ++ node;
l[y] = l[x], r[y] = r[x];
sum[y] = sum[x] + type;
if(s == e)return ;
int mid = s + e >> 1;
if(pos <= mid){
build(s , mid , l[x] , l[y] , pos , type);
}
else build(mid + 1, e , r[x] , r[y] , pos , type);
}
int query(int s,int e,int k){
if(s == e)return s;
int mid = s+e >> 1;
int suml = 0, sumr = 0;
for(int i = 1;i <= lcnt; ++i){
suml += sum[l[lsl[i]]];//把1到l的左子树的和累加
}
for(int i = 1;i <= rcnt; ++i){
sumr += sum[l[lsr[i]]];
}
if(sumr - suml >= k){
for(int i = 1;i <= lcnt; ++i){
lsl[i] = l[lsl[i]];
}
for(int i = 1;i <= rcnt; ++i){
lsr[i] = l[lsr[i]];
}
return query(s , mid , k);
}
else {
for(int i = 1;i <= lcnt; ++i){
lsl[i] = r[lsl[i]];
}
for(int i = 1;i <= rcnt; ++i){
lsr[i] = r[lsr[i]];
}
return query(mid+1, e, k - sumr + suml);
}
}
int main(){
#ifndef ONLINE_JUDGE
freopen("THUNDER.in","r",stdin);
freopen("THUNDER.out","w",stdout);
#endif
int i,j;
For(i ,1 ,n){
ls[++cnt] = a[i];
}
For(i ,1 ,m){
scanf("%s", ss);
if(ss[0] == 'Q'){
}
else {
}
}
sort(ls+1 , ls+cnt+1);
cnt = unique(ls+1, ls+cnt+1) - (ls+1);
For(i ,1 ,n){
int pos = lower_bound(ls+1 ,ls+cnt+1, a[i]) - ls;
for(j = i; j <= n; j += lowbit(j)){
build(1 , cnt , tree[j] , tree[j] , pos , 1);//用原来这个节点的信息，节省空间
}
}
For(i ,1 ,m){
if(K[i]){
lcnt = 0,rcnt = 0;
for(j = A[i] - 1; j ; j -= lowbit(j)){//为了求前缀和，要把遍历到的点加入数组
lsl[++lcnt] = tree[j];
}
for(j = B[i]; j ;j -= lowbit(j)){
lsr[++rcnt] = tree[j];
}
printf("%d\n", ls[query(1 , cnt ,K[i])]);
}
else{
int val = a[A[i]];
int pos = lower_bound(ls + 1,ls + cnt + 1,val) - ls;
for(j = A[i];j <= n; j += lowbit(j)){
build(1 , cnt, tree[j], tree[j] , pos, -1);//这里有点特殊，要先把原先这个数做更新的区间全部删掉信息，再在下面更新
}
a[A[i]] = B[i];
pos = lower_bound(ls + 1,ls + cnt + 1,B[i]) - ls;
for(j = A[i];j <= n; j += lowbit(j)){
build(1 , cnt, tree[j] , tree[j] , pos, 1);
}
}
}

return 0;
}


©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客