Cod sursa(job #1810279)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 19 noiembrie 2016 20:42:19
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.36 kb
#include <bits/stdc++.h>

using namespace std;

struct Node{
    int key;
    int priority;

    shared_ptr<Node> l, r;

    Node(int k, int p, const shared_ptr<Node> &_l, const shared_ptr<Node> &_r){
        key = k;
        priority = p;
        l = _l;
        r = _r;
    }
};

shared_ptr<Node> root, NIL;

void initTreap(){
    srand(time(nullptr));
    NIL.reset(new Node(-1, 0, nullptr, nullptr));
    root = NIL;
}

void rotateToRight(shared_ptr<Node> &T){
    shared_ptr<Node> aux = T->l;
    T->l = aux->r;
    aux->r = T;

    T = aux;
}

void rotateToLeft(shared_ptr<Node> &T){
    shared_ptr<Node> aux = T->r;
    T->r = aux->l;
    aux->l = T;

    T = aux;
}

void balance(shared_ptr<Node> &T){
    if (T->l->priority > T->priority)
        rotateToRight(T);

    if (T->r->priority > T->priority)
        rotateToLeft(T);
}

void insert(shared_ptr<Node> &T, int key, int priority = 1 + rand()){
    if (T == NIL){
        T.reset(new Node(key, priority, NIL, NIL));
    }
    else{
        if (key < T->key)
            insert(T->l, key, priority);
        else if (key > T->key)
            insert(T->r, key, priority);

        balance(T);
    }
}

void erase(shared_ptr<Node> &T, int key){
    if (T == NIL)
        return;

    if (T->key == key){
        if (T->l == NIL && T->r == NIL){
            T = NIL;
        }
        else{
            if (T->l->priority > T->r->priority){
                rotateToRight(T);
                erase(T->r, key);
            }
            else{
                rotateToLeft(T);
                erase(T->l, key);
            }
        }
    }
    else if (key < T->key)
        erase(T->l, key);
    else
        erase(T->r, key);
}

bool find(shared_ptr<Node> &T, int key){
    if (T == NIL)
        return false;

    if (T->key == key)
        return true;

    if (key < T->key)
        return find(T->l, key);
    else
        return find(T->r, key);
}

int main()
{
    ifstream in("hashuri.in");
    ofstream out("hashuri.out");

    int N;
    in >> N;

    initTreap();

    while (N--){
        int t;
        in >> t;

        if (t == 1){
            int x;
            in >> x;
            insert(root, x);
        }
        else if (t == 2){
            int x;
            in >> x;
            erase(root, x);
        }
        else{
            int x;
            in >> x;
            out << find(root, x) << "\n";
        }
    }

    return 0;
}