Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- #define int long long
- using namespace std;
- mt19937 gen(chrono::steady_clock::now().time_since_epoch().count());
- struct node {
- int x = 0, y = gen();
- node *l = nullptr;
- node *r = nullptr;
- node() = default;
- node(int& x) {
- this->x = x;
- }
- };
- node* merge(node* a, node* b) {
- if (a == nullptr)
- return b;
- if (b == nullptr)
- return a;
- if (a->y > b->y) {
- a->r = merge(a->r, b);
- return a;
- } else {
- b->l = merge(a, b->l);
- return b;
- }
- }
- pair<node*, node*> split(node* a, int x) {
- if (a == nullptr)
- return {nullptr, nullptr};
- if (a->x < x) {
- auto spl_R = split(a->r, x);
- a->r = spl_R.first;
- return {a, spl_R.second};
- } else {
- auto spl_L = split(a->l, x);
- a->l = spl_L.second;
- return {spl_L.first, a};
- }
- }
- node* find(node* a, int x) {
- if (a == nullptr)
- return nullptr;
- if (a->x == x)
- return a;
- if (a->x > x)
- return find(a->l, x);
- if (a->x < x)
- return find(a->r, x);
- return nullptr;
- }
- node* insert(node* a, int x) {
- if (find(a, x) != nullptr)
- return a;
- node* A = new node(x);
- auto spl = split(a, x);
- A = merge(spl.first, A);
- A = merge(A, spl.second);
- return A;
- }
- node* erase(node* a, int x) {
- auto spl = split(a, x);
- auto spl_L = split(spl.second, x + 1);
- a = merge(spl.first, spl_L.second);
- return a;
- }
- node* getRight(node* a) {
- if (a == nullptr)
- return nullptr;
- return (a->r == nullptr ? a : getRight(a->r));
- }
- node* getLeft(node* a) {
- if (a == nullptr)
- return nullptr;
- return (a->l == nullptr ? a : getLeft(a->l));
- }
- node* next(node* a, int x) {
- auto spl = split(a, x + 1);
- auto ans = getLeft(spl.second);
- a = merge(spl.first, spl.second);
- return ans;
- }
- node* prev(node* a, int x) {
- auto spl = split(a, x);
- auto ans = getRight(spl.first);
- a = merge(spl.first, spl.second);
- return ans;
- }
- void display(node* a) {
- if (a == nullptr)
- return;
- display(a->l);
- cout << a->x << ' ';
- display(a->r);
- }
- signed main() {
- ios::sync_with_stdio(false);
- cin.tie(nullptr);
- // freopen("input.txt", "r", stdin);
- string s;
- node* dd = nullptr;
- while (cin >> s) {
- if (s == "insert") {
- int x;
- cin >> x;
- dd = insert(dd, x);
- }
- if (s == "delete") {
- int x;
- cin >> x;
- dd = erase(dd, x);
- }
- if (s == "exists") {
- int x;
- cin >> x;
- if (find(dd, x) == nullptr)
- cout << "false\n";
- else
- cout << "true\n";
- }
- if (s == "next") {
- int x;
- cin >> x;
- auto ans = next(dd, x);
- cout << (ans == nullptr ? "none" : to_string(ans->x)) << '\n';
- }
- if (s == "prev") {
- int x;
- cin >> x;
- auto ans = prev(dd, x);
- cout << (ans == nullptr ? "none" : to_string(ans->x)) << '\n';
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement