宝石管理系统

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;
}
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值