Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <time.h>
- #include <stdio.h>
- #include <stdlib.h>
- using namespace std;
- struct node {
- int x;
- int cnt;
- node * left;
- node * right;
- node(int x): x(x), cnt(1), left(nullptr), right(nullptr) { }
- };
- typedef node* tree;
- typedef pair<tree, tree> ptt;
- int get_cnt(tree v) {
- return v ? v->cnt : 0;
- }
- void update_cnt(tree v) {
- if (v)
- v->cnt = 1 + get_cnt(v->left) + get_cnt(v->right);
- }
- tree merge(tree a, tree b) {
- if (a == nullptr)
- return b;
- if (b == nullptr)
- return a;
- if (a->x > b->x)
- swap(a, b);
- if (rand() % (get_cnt(a) + get_cnt(b)) < get_cnt(a)) {
- a->right = merge(a->right, b);
- update_cnt(a);
- return a;
- } else {
- b->left = merge(a, b->left);
- update_cnt(b);
- return b;
- }
- }
- ptt split(tree v, int val) {
- if (v == nullptr)
- return make_pair(nullptr, nullptr);
- if (v->x > val) {
- ptt ab = split(v->left, val);
- v->left = ab.second;
- update_cnt(v);
- ab.second = v;
- return ab;
- } else if (v->x <= val) {
- ptt ab = split(v->right, val);
- v->right = ab.first;
- update_cnt(v);
- ab.first = v;
- return ab;
- }
- }
- tree insert(tree v, int val) {
- ptt ab = split(v, val);
- return merge(merge(ab.first, new node(val)), ab.second);
- }
- tree remove(tree v, int val) {
- ptt ab = split(v, val - 1);
- ptt bc = split(ab.second, val);
- return merge(ab.first, bc.second);
- }
- void print(tree v) {
- if (v) {
- print(v->left);
- cout << v->x << " ";
- print(v->right);
- }
- }
- int main() {/*
- ios_base::sync_with_stdio(false);
- cin.tie(0);
- cout.tie(0);*/
- int n;
- cin >> n;
- srand(time(0));
- tree root = nullptr;
- for (int i = 0; i < n; ++i) {
- string type;
- cin >> type;
- int k;
- cin >> k;
- if (type == "+1") {
- root = insert(root, k);
- }
- if (type == "-1") {
- root = remove(root, k);
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement