Cod sursa(job #1350116)

Utilizator andreiiiiPopa Andrei andreiiii Data 20 februarie 2015 17:51:29
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.66 kb
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int key, pry, size;
    Node *left, *right;
    Node(const int _key):
        key(_key), pry(get_random()), size(1), left(NULL), right(NULL) {}
private:
    static int get_random() {
        return (rand() << 16) + rand();
    }
};

inline int getSize(Node* node) {
    return node == NULL ? 0: node->size;
}

inline void update(Node* node) {
    node->size = 1 + getSize(node->left) + getSize(node->right);
}

pair<Node*, Node*> split(Node* root, int val) {
    if (root == NULL)
        return make_pair((Node*) NULL, (Node*) NULL);

    if (val <= root->key) {
        pair<Node*, Node*> leftsplit = split(root->left, val);
        root->left = leftsplit.second;
        update(root);
        leftsplit.second = root;
        return leftsplit;
    } else {
        pair<Node*, Node*> rightsplit = split(root->right, val);
        root->right = rightsplit.first;
        update(root);
        rightsplit.first = root;
        return rightsplit;
    }
}

Node* merge(Node *left, Node *right) {
    if (left == NULL) return right;
    if (right == NULL) return left;

    if (left->pry > right->pry) {
        left->right = merge(left->right, right);
        update(left);
        return left;
    } else {
        right->left = merge(left, right->left);
        update(right);
        return right;
    }
}

Node* find(Node* root, int val) {
    if (root == NULL) return NULL;
    if (root->key < val) return find(root->right, val);
    else if (root->key > val) return find(root->left, val);
    return root;
}

Node* insert(Node* root, int val) {
    if (find(root, val) != NULL) return root;
    pair<Node*, Node*> splt = split(root, val);
    return merge(merge(splt.first, new Node(val)), splt.second);
}

Node* remove(Node* root, int val) {
    if (root == NULL) return NULL;
    if (val < root->key) {
        root->left = remove(root->left, val);
        update(root);
        return root;
    } else if (val > root->key) {
        root->right = remove(root->right, val);
        update(root);
        return root;
    } else {
        Node* aux = merge(root->left, root->right);
        delete root;
        return aux;
    }
}

int main() {
    ifstream fin("hashuri.in");
    ofstream fout("hashuri.out");
    
    srand(time(0));

    int Q;
    fin >> Q;

    Node* root = NULL;
    while (Q--) {
        int op, x;
        fin >> op >> x;

        if (op == 1) {
            root = insert(root, x);
        } else if (op == 2) {
            root = remove(root, x);
        } else {
            fout << (find(root, x) == NULL ? 0: 1) << '\n';
        }
    }
    
    //fout << rand() << '\n';
     
    fin.close();
    fout.close();
}