实际上并不是主席树……只是有点像。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define mid (l+r>>1)
//离散化之后的值是大一点的
const int MAXN = 200000 + 5;
int T[MAXN], tcnt;
//主席树每次修改稳定增加18个新节点
//每个元素加进来,修改的主席树由树状数组的复杂可以另外算,应该是至多增加100个节点,防止翻车直接330算了
int cnt[MAXN * 330], Lson[MAXN * 330], Rson[MAXN * 330];
int a[MAXN], val[MAXN], cn;
inline int Build(int l, int r) {
int rt = ++tcnt;
cnt[rt] = 0;
if(l < r) {
Lson[rt] = Build(l, mid);
Rson[rt] = Build(mid + 1, r);
}
return rt;
}
inline void _Update(int &rt, int l, int r, int x, int d) {
if(!rt)
rt = ++tcnt;
cnt[rt] += d;
if(l < r) {
if(x <= mid)
_Update(Lson[rt], l, mid, x, d);
else
_Update(Rson[rt], mid + 1, r, x, d);
}
}
//把x位置的数加入主席树森林
inline void Update1(int x, int v) {
for(int i = x; i <= cn; i += (i & -i))
_Update(T[i], 1, cn, a[x], 1);
}
//把x位置改成v
inline void Update2(int x, int v) {
for(int i = x; i <= cn; i += (i & -i))
_Update(T[i], 1, cn, a[x], -1);
a[x] = v;
for(int i = x; i <= cn; i += (i & -i))
_Update(T[i], 1, cn, a[x], 1);
}
const int MAXLOGN = 80;
int Lroot[MAXLOGN], Rroot[MAXLOGN], ltop, rtop;
//[l,r]第k大
inline int Query(int l, int r, int k) {
--l, ltop = rtop = 0;
for(int i = l; i >= 1; i -= (i & -i))
Lroot[++ltop] = T[i];
for(int i = r; i >= 1; i -= (i & -i))
Rroot[++rtop] = T[i];
int LL = 1, RR = cn, MID;
while(1) {
MID = LL + RR >> 1;
int sum = 0;
for(int i = 1; i <= ltop; ++i)
sum -= cnt[Lson[Lroot[i]]];
for(int i = 1; i <= rtop; ++i)
sum += cnt[Lson[Rroot[i]]];
if(LL == MID) {
if(sum >= k)
return val[LL];
return val[RR];
}
if(k <= sum) {
//在左儿子
for(int i = 1; i <= ltop; ++i)
Lroot[i] = Lson[Lroot[i]];
for(int i = 1; i <= rtop; ++i)
Rroot[i] = Lson[Rroot[i]];
RR = MID;
} else {
//在右儿子
for(int i = 1; i <= ltop; ++i)
Lroot[i] = Rson[Lroot[i]];
for(int i = 1; i <= rtop; ++i)
Rroot[i] = Rson[Rroot[i]];
k -= sum;
LL = MID + 1;
}
}
}
struct Q {
char type;
int l, r, x;
} q[MAXN];
int main() {
#ifdef Yinku
freopen("Yinku.in", "r", stdin);
#endif // Yinku
/*int c=100000;//n的上界
int cntlog=0;
for(int x=1;x<=c;++x){
for(int i = x; i <= 200000; i += (i & -i))//cn的上界
cntlog+=18;
}
printf("cntlog=%d
",cntlog/200000);*/
int n, m;
scanf("%d%d", &n, &m);
cn = 0;
for(int i = 1; i <= n ; ++i) {
scanf("%d", &a[i]);
val[++cn] = a[i];
}
for(int i = 1; i <= m; ++i) {
char s[2];
scanf("%s", s);
if(s[0] == 'Q') {
q[i].type = 'Q';
scanf("%d%d%d", &q[i].l, &q[i].r, &q[i].x);
} else {
q[i].type = 'C';
scanf("%d%d", &q[i].l, &q[i].x);
val[++cn] = q[i].x;
}
}
sort(val + 1, val + 1 + cn);
cn = unique(val + 1, val + 1 + cn) - (val + 1);
for(int i = 1; i <= n; ++i)
a[i] = lower_bound(val + 1, val + 1 + cn, a[i]) - val;
for(int i = 1; i <= m; ++i)
if(q[i].type == 'C')
q[i].x = lower_bound(val + 1, val + 1 + cn, q[i].x) - val;
tcnt = 0;
T[0] = Build(1, cn);
for(int i = 1; i <= n ; ++i)
Update1(i, a[i]);
for(int i = 1; i <= m; ++i) {
if(q[i].type == 'Q')
printf("%d
", Query(q[i].l, q[i].r, q[i].x));
else
Update2(q[i].l, q[i].x);
}
return 0;
}