#include #include using namespace std; mt19937 rng(time(0)); struct Node { int x, y; int tSize; Node* left; Node* right; Node(int x_) { x = x_; y = rng(); tSize = 1; left = nullptr; right = nullptr; } }; int tRecalc(Node* t) { if (t == nullptr) return 0; t->tSize = 1; if (t->left) t->tSize += t->left->tSize; if (t->right) t->tSize += t->right->tSize; return t->tSize; } int GetSize(Node* t) { if (t == nullptr) return 0; return t->tSize; } pair Split(Node* t, int x) { if (t == nullptr) return { nullptr, nullptr }; if (x < t->x) { pair leftres = Split(t->left, x); t->left = leftres.second; tRecalc(t); return { leftres.first, t }; } else { pair rightres = Split(t->right, x); t->right = rightres.first; tRecalc(t); return { t, rightres.second }; } } Node* Merge(Node* l, Node* r) { if (l == nullptr) return r; if (r == nullptr) return l; if (l->y >= r->y) { l->right = Merge(l->right, r); tRecalc(l); return l; } else { r->left = Merge(l, r->left); tRecalc(r); return r; } } Node* Insert(Node* t, int x) { Node* newnode = new Node(x); //auto [L, R] = Split(t, x); auto lr = Split(t, x); return Merge(Merge(lr.first, newnode), lr.second); } Node* Remove(Node* t, int x) { auto lr = Split(t, x); auto temp = Split(lr.first, x - 1); //добавить освобождение памяти return Merge(temp.first, lr.second); } bool TreapFind(Node* t, int x) { if (t == nullptr) { return 0; } if (x == t->x) return 1; if (x > t->x) return TreapFind(t->right, x); if (x < t->x) return TreapFind(t->left, x); } Node* kth(Node* t, int k) { if (t == nullptr) return nullptr; if (GetSize(t->left) == k - 1) return t; if (GetSize(t->left) > k - 1) return kth(t->left, k); if (GetSize(t->left) == k - 1) return kth(t->left, k - GetSize(t->left) - 1); } void TreapOutput(Node* t, int depth) { if (t == nullptr) return; TreapOutput(t->left, depth + 1); for (int i = 0; i < depth; i++) { cout << " "; } cout << t->x << endl; TreapOutput(t->right, depth + 1); } int main() { /*int size = 5; Node* root = new Node(rng() % 100); for (int i = 0; i < size; i++) { root = Insert(root, rng() % 100); } TreapOutput(root, 0);*/ char cmd; int cnt; cin >> cnt; int x; Node* t = nullptr; //Node* t = root; for (int i = 0; i < cnt; i++) { cin >> cmd; if (cmd == '+') { cin >> x; t = Insert(t, x); } if (cmd == '-') { cin >> x; t = Remove(t, x); } if (cmd == '?') { cin >> x; if (TreapFind(t, x)) cout << "YES" << endl; else cout << "NO" << endl; } if (cmd == 's') { if (!t) { cout << 0 << endl; } else cout << t->tSize << endl; } if (cmd == 'p') { TreapOutput(t, 0); } if (cmd == 'k') { int k; cin >> k; Node* xk = kth(t, k); if (xk == nullptr) { cout << "No kth element" << endl; } else cout << xk->x << endl; } } return 0; }