Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <random>
- #include <iostream>
- using namespace std;
- mt19937 gen;
- struct node {
- int key, sz, prior;
- node *l = nullptr, *r = nullptr;
- ~node() {
- delete l;
- delete r;
- }
- node(int v) {
- key = v;
- sz = 1;
- prior = gen();
- }
- };
- void upd(node* v) {
- if (!v)
- return;
- v->sz = 1;
- if (v->l) v->sz += v->l->sz;
- if (v->r) v->sz += v->r->sz;
- }
- node* merge(node* l, node* r) {
- if (!l) return r;
- if (!r) return l;
- if (l->prior > r->prior) {
- l->r = merge(l->r, r);
- upd(l);
- return l;
- } else {
- r->l = merge(l, r->l);
- upd(r);
- return r;
- }
- }
- // <= k, > k
- pair<node*, node*> split_key(node* v, int k) {
- if (!v) return { nullptr, nullptr };
- if (v->key <= k) {
- auto p = split_key(v->r, k);
- v->r = nullptr;
- upd(v);
- return { merge(v, p.first), p.second };
- } else {
- auto p = split_key(v->l, k);
- v->l = nullptr;
- upd(v);
- return { p.first, merge(p.second, v) };
- }
- }
- void dfs(node* v) {
- if (!v)
- return;
- dfs(v->l);
- cout << v->key << ' ';
- dfs(v->r);
- }
- int main(int argc, char** argv) {
- ios::sync_with_stdio(false), cin.tie(0);
- node* root = nullptr;
- int m;
- cin >> m;
- while (m--) {
- int t;
- cin >> t;
- // t = 1 <-> insert a
- // t = 2 <-> remove all instances of a
- // t = 3 <-> #{x \in Treap | x <= a}
- // t = 4 <-> print the entire treap
- if (t == 1) {
- int v;
- cin >> v;
- node* nv = new node(v);
- auto d = split_key(root, v);
- root = merge(d.first, merge(nv, d.second));
- } else if (t == 2) {
- int v;
- cin >> v;
- auto d = split_key(root, v);
- auto p = split_key(d.first, v - 1);
- delete p.second;
- root = merge(p.first, d.second);
- } else if (t == 3) {
- int v;
- cin >> v;
- auto d = split_key(root, v);
- int sz = 0;
- if (d.first)
- sz = d.first->sz;
- root = merge(d.first, d.second);
- cout << sz << endl;
- } else if (t == 4) {
- dfs(root);
- cout << endl;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement