Advertisement
Guest User

Untitled

a guest
Apr 5th, 2020
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.07 KB | None | 0 0
  1. #include <random>
  2. #include <iostream>
  3. using namespace std;
  4. mt19937 gen;
  5.  
  6. struct node {
  7.   int key, sz, prior;
  8.   node *l = nullptr, *r = nullptr;
  9.   ~node() {
  10.     delete l;
  11.     delete r;
  12.   }
  13.   node(int v) {
  14.     key = v;
  15.     sz = 1;
  16.     prior = gen();
  17.   }
  18. };
  19.  
  20. void upd(node* v) {
  21.   if (!v)
  22.     return;
  23.   v->sz = 1;
  24.   if (v->l) v->sz += v->l->sz;
  25.   if (v->r) v->sz += v->r->sz;
  26. }
  27.  
  28. node* merge(node* l, node* r) {
  29.   if (!l) return r;
  30.   if (!r) return l;
  31.   if (l->prior > r->prior) {
  32.     l->r = merge(l->r, r);
  33.     upd(l);
  34.     return l;
  35.   } else {
  36.     r->l = merge(l, r->l);
  37.     upd(r);
  38.     return r;
  39.   }
  40. }
  41.  
  42. // <= k, > k
  43. pair<node*, node*> split_key(node* v, int k) {
  44.   if (!v) return { nullptr, nullptr };
  45.   if (v->key <= k) {
  46.     auto p = split_key(v->r, k);
  47.     v->r = nullptr;
  48.     upd(v);
  49.     return { merge(v, p.first), p.second };
  50.   } else {
  51.     auto p = split_key(v->l, k);
  52.     v->l = nullptr;
  53.     upd(v);
  54.     return { p.first, merge(p.second, v) };
  55.   }
  56. }
  57.  
  58. void dfs(node* v) {
  59.   if (!v)
  60.     return;
  61.   dfs(v->l);
  62.   cout << v->key << ' ';
  63.   dfs(v->r);
  64. }
  65.  
  66. int main(int argc, char** argv) {
  67.   ios::sync_with_stdio(false), cin.tie(0);
  68.   node* root = nullptr;
  69.  
  70.   int m;
  71.   cin >> m;
  72.   while (m--) {
  73.     int t;
  74.     cin >> t;
  75.     // t = 1 <-> insert a
  76.     // t = 2 <-> remove all instances of a
  77.     // t = 3 <-> #{x \in Treap | x <= a}
  78.     // t = 4 <-> print the entire treap
  79.     if (t == 1) {
  80.       int v;
  81.       cin >> v;
  82.       node* nv = new node(v);
  83.       auto d = split_key(root, v);
  84.       root = merge(d.first, merge(nv, d.second));
  85.     } else if (t == 2) {
  86.       int v;
  87.       cin >> v;
  88.       auto d = split_key(root, v);
  89.       auto p = split_key(d.first, v - 1);
  90.       delete p.second;
  91.       root = merge(p.first, d.second);
  92.     } else if (t == 3) {
  93.       int v;
  94.       cin >> v;
  95.       auto d = split_key(root, v);
  96.       int sz = 0;
  97.       if (d.first)
  98.         sz = d.first->sz;
  99.       root = merge(d.first, d.second);
  100.       cout << sz << endl;
  101.     } else if (t == 4) {
  102.       dfs(root);
  103.       cout << endl;
  104.     }
  105.   }
  106. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement