fhq treap的练手题
原题地址:宝石管理系统
没什么好讲的,直接上代码
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<ctime>
#include<algorithm>
using namespace std;
#define MAXN 300000
int T, m, SIZE, val, opt, n, cnt, root;
struct node {
int l, r, val, key, size;
} t[MAXN];
inline int read() {
int s = 0, w = 1;
char c = getchar();
for (; !isdigit(c); c = getchar()) if (c == '-') w = -1;
for (; isdigit(c); c = getchar()) s = (s << 1) + (s << 3) + (c ^ 48);
return s * w;
}
inline int New(int val) {
t[++cnt].val = val, t[cnt].key = rand() * rand(), t[cnt].size = 1;
return cnt;
}
inline void update(int now) {
t[now].size = t[t[now].l].size + t[t[now].r].size + 1;
}
inline void Split(int now, int w, int &u, int &v) {
if (!now) u = v = 0;
else {
if (t[now].val <= w) u = now, Split(t[now].r, w, t[now].r, v);
else v = now, Split(t[now].l, w, u, t[now].l);
update(now);
}
}
inline int Merge(int u, int v) {
if (!u || !v) return u + v;
if (t[u].key < t[v].key) {
t[u].r = Merge(t[u].r, v);
update(u);
return u;
}
else {
t[v].l = Merge(u, t[v].l);
update(v);
return v;
}
}
inline void Insert(int val) {
int x = 0, y = 0;
Split(root, val, x, y);
root = Merge(Merge(x, New(val)), y);
}
inline int Kth(int now, int sum) {
while (1) {
if (sum <= t[t[now].l].size) now = t[now].l;
else if (sum == t[t[now].l].size + 1) return now;
else sum -= t[t[now].l].size + 1 , now = t[now].r;
}
}
int main() {
srand(time(0));
T = read(), m = read();
SIZE = T;
while (T--) {
val = read();
Insert(val);
}
while (m--) {
opt = read(), n = read();
if (opt == 1) {
printf("%d\n", t[Kth(root, SIZE + 1 - n)].val);
}
else {
Insert(n);
SIZE++;
}
}
return 0;
}