宝石管理系统(Splay维护重复元素)
这题的Splay维护关键字是元素的值,而不是序列下标;
传送门
题面
Code
#include <iostream>
#include <cstring>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef long long ll;
const int N = 200000 + 10;
struct Tree{
int s[2];
int val,fa;
int cnt;
int sz;
void init(int _v,int p){
val = _v,fa = p;
s[0] = s[1] = 0;
sz = cnt = 1;
}
}tr[N];
#define lc (tr[p].s[0])
#define rc (tr[p].s[1])
void push_up(int p){
tr[p].sz = tr[lc].sz + tr[rc].sz + tr[p].cnt;
}
int root;
int rotate(int x){
int y = tr[x].fa,z = tr[y].fa;
int k = tr[y].s[1] == x;
tr[z].s[tr[z].s[1] == y] = x,tr[x].fa = z;
tr[y].s[k] = tr[x].s[k^1],tr[tr[x].s[k^1]].fa = y;
tr[x].s[k^1] = y,tr[y].fa = x;
push_up(y);
push_up(x);
}
void splay(int x,int k){
while(tr[x].fa != k){
int y = tr[x].fa,z = tr[y].fa;
if(z != k){
//折线形
if((tr[y].s[0] == x) ^ (tr[z].s[0] == y)){
rotate(x);
}
else rotate(y);
}
rotate(x);
}
if(!k) root = x;
}
int idx;
void insert(int val){
int u = root,fa = 0;
while(u){
if(tr[u].val == val){
++tr[u].cnt;
push_up(u);
//注意不要搞到0上面去
if(fa) push_up(fa);
splay(u,0);
return;
}
fa = u,u = tr[u].s[tr[u].val < val];
}
//这个结点还不存在
u = ++idx;
if(fa){
int k = tr[fa].val < val;
tr[fa].s[k] = u;
}
tr[u].init(val,fa);
splay(u,0);
}
int kth(int p,int k){//第k大
if(tr[rc].sz >= k) return kth(rc,k);
else if(tr[rc].sz + tr[p].cnt >= k){
return tr[p].val;
}
else{
return kth(lc,k-tr[rc].sz-tr[p].cnt);
}
}
void solve(){
int n,q;
cin >> n >> q;
for(int i=1;i<=n;++i){
int x;
cin >> x;
insert(x);
}
while(q--){
int opt,k;
cin >> opt >> k;
if(opt == 1){
cout << kth(root,k) << '\n';
}
else{
insert(k);
}
}
}
signed main(){
std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
solve();
return 0;
}