Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- struct node
- {
- long long v, p, s;
- node *l, *r;
- node()
- {
- l = r = NULL;
- v = p = 0;
- s = 0;
- }
- };
- typedef long long int ll;
- typedef node* pnode;
- ll n, q;
- char c;
- ll sz(pnode t)
- {
- if (t)return t->s;
- return 0;
- }
- void upsz(pnode &t)
- {
- if (!t)return;
- t->s = sz(t->r) + sz(t->l) + 1;
- }
- void split(pnode t, pnode &l, pnode &r,ll k)
- {
- if (!t)l = r = NULL;
- else if (t->v <= k)split(t->r,t->r,r,k),l = t;
- else split(t->l, l, t->l, k), r = t;
- upsz(t);
- }
- void merge(pnode &t, pnode l, pnode r)
- {
- if (!l)t = r;
- else if (!r)t = l;
- else if (l->p > r->p)merge(l->r,l->r, r), t = l;
- else merge(r->l, l, r->l), t = r;
- upsz(t);
- }
- void ins(pnode nt, pnode &t)
- {
- if (!t || !(t->s))t = nt;
- else if (t->p < nt->p)split(t, nt->l, nt->r, nt->v), t = nt;
- else if (nt->v <= t->v)ins(nt, t->l);
- else ins(nt, t->r);
- upsz(t);
- }
- void era(pnode &t, ll k)
- {
- if (!t)return;
- else if (t->v == k){ pnode te = t; merge(t, t->l, t->r); te = NULL; }
- else if (t->v > k)era(t->l, k);
- else era(t->r, k);
- upsz(t);
- }
- bool find(pnode t,ll va)
- {
- if (!t || t->s==0)return false;
- if (t->v == va)return 1;
- if (t->v > va)return find(t->l,va);
- else return find(t->r, va);
- }
- pnode ne(ll va)
- {
- pnode r=new node();
- r->l = r->r = NULL;
- r->s = 1;
- r->v = va;
- r->p = rand();
- return r;
- }
- ll kth(pnode &t, ll k,ll l)
- {
- if (l + sz(t->l)+1== k)
- return t->v;
- else if (k > l + sz(t->l))
- return kth(t->r, k, l + sz(t->l)+1);
- else
- return kth(t->l,k,l);
- }
- ll co(pnode &t,ll x)
- {
- if (!t)return 0;
- if (t->v == x)return sz(t->l);
- if (t->v < x)return sz(t->l) + 1 + co(t->r, x);
- return co(t->l, x);
- }
- int main()
- {
- ios::sync_with_stdio(false);
- cin.tie(0);
- cout.tie(0);
- pnode t = new node();
- cin >> q;
- while (q--)
- {
- cin >> c >> n;
- if (c == 'I')
- {
- if (find(t, n))
- continue;
- ins(ne(n), t);
- }
- else if (c == 'D')
- era(t, n);
- else if (c == 'K')
- {
- if (t->s < n)cout << "invalid";
- else cout << kth(t, n,0);
- cout << "\n";
- }
- else
- cout << co(t, n) << "\n";
- }
- return 0;
- }
Add Comment
Please, Sign In to add comment