1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
| #include <bits/stdc++.h> #define INF 0x7f7f7f7f #define flag cur->fa->fa!=tar&&cur->fa->fa->s[sn]==cur->fa using namespace std; template <class T> inline void read(T &x) { x = 0; int c = getchar(), f = 1; for (; !isdigit(c); c = getchar()) if (c == 45) f = -1; for (; isdigit(c); c = getchar()) (x *= 10) += f*(c-'0'); } int n, mi, det, tot; struct SplayNode { SplayNode *s[2], *fa; int val, w, sz; void update() {sz = w+(s[0]?s[0]->sz:0)+(s[1]?s[1]->sz:0);} } ; struct SplayTree { SplayNode* rt; SplayNode* newnode(int _val) { SplayNode* v = new SplayNode; v->s[0] = v->s[1] = v->fa = NULL; v->val = _val, v->w = v->sz = 1; return v; } SplayTree() { rt = newnode(-INF), rt->s[1] = newnode(INF); rt->s[1]->fa = rt, rt->update(); } void rotate(SplayNode* v, bool sn) { SplayNode* f = v->fa; f->s[sn^1] = v->s[sn], v->fa = f->fa; if (f->s[sn^1]) f->s[sn^1]->fa = f; if (v->fa) v->fa->s[f == f->fa->s[1]] = v; v->s[sn] = f, f->fa = v, f->update(), v->update(); } void splay(SplayNode* cur, SplayNode* tar) { while (cur != tar && cur->fa != tar) { bool sn = cur->fa->s[1] == cur; if (flag) rotate(cur->fa, sn^1); rotate(cur, sn^1); } if (cur->fa == tar) rotate(cur, cur->fa->s[0] == cur); if (tar == rt) rt = cur; } SplayNode* predecessor(int _val) { SplayNode *cur = rt, *cpy = rt; for (; cur; cur = cur->s[_val > cur->val]) if (cur->val < _val) cpy = cur; return cpy; } SplayNode* successor(int _val) { SplayNode *cur = rt, *cpy = rt; for (; cur; cur = cur->s[_val >= cur->val]) if (cur->val > _val) cpy = cur; return cpy; } SplayNode* get_kth(SplayNode* v, int k) { int lsz = v->s[0] ? v->s[0]->sz : 0; if (k <= lsz) return get_kth(v->s[0], k); if (k > lsz+v->w) return get_kth(v->s[1], k-lsz-v->w); return v; } void insert(int _val) { if (_val+det < mi) return; SplayNode* pre = predecessor(_val); SplayNode* suc = successor(_val); splay(pre, rt), splay(suc, rt->s[1]); if (suc->s[0]) suc->s[0]->w++, suc->s[0]->sz++; else suc->s[0] = newnode(_val), suc->s[0]->fa = suc; suc->update(), rt->update(); } void remove(int _val) { SplayNode* pre = get_kth(rt, 1); SplayNode* suc = successor(_val-1); splay(pre, rt), splay(suc, rt->s[1]); if (suc->s[0]) tot += suc->s[0]->sz; suc->s[0] = NULL, suc->update(), rt->update(); } } BBST; int main() { read(n), read(mi); for (int x; n; n--) { char opt[1]; scanf("%s", opt), read(x); if (opt[0] == 'I') BBST.insert(x-det); if (opt[0] == 'A') det += x; if (opt[0] == 'S') BBST.remove(mi-(det-=x)); if (opt[0] == 'F') { x = BBST.rt->sz-x-1; if (x < 1 || x > BBST.rt->sz-2) puts("-1"); else printf("%d\n", BBST.get_kth(BBST.rt, x+1)->val+det); } } return printf("%d\n", tot), 0; }
|