Cod sursa(job #1518604)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 6 noiembrie 2015 00:03:25
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.21 kb
#include <bits/stdc++.h>

using namespace std;

struct Node
{
    int key;
    int priority;

    Node *st, *dr;

    Node(const int k, const int p, Node *l, Node *r)
    {
        key = k;
        priority = p;
        st = l;
        dr = r;
    }
};

Node *Root, *NIL;

void initTreap()
{
    NIL = new Node(0, 0, nullptr, nullptr);
    Root = NIL;
}

void rotateToLeft(Node *&T)
{
    Node *aux = T->dr;
    T->dr = aux->st;
    aux->st = T;

    T = aux;
}

void rotateToRight(Node *&T)
{
    Node *aux = T->st;
    T->st = aux->dr;
    aux->dr = T;

    T = aux;
}

void balance(Node *&T)
{
    if (T->st->priority > T->priority)
        rotateToRight(T);
    else if (T->dr->priority > T->priority)
        rotateToLeft(T);
}

void insert(Node *&T, const int key, const int priority)
{
    if (T == NIL)
    {
        T = new Node(key, priority, NIL, NIL);
    }
    else
    {
        if (key < T->key)
            insert(T->st, key, priority);
        else if (key > T->key)
            insert(T->dr, key, priority);

        balance(T);
    }
}

bool find(Node *&T, const int key)
{
    if (T == NIL)
        return false;

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

    if (key < T->key)
        return find(T->st, key);
    else
        return find(T->dr, key);
}

void erase(Node *&T, const int key)
{
    if (T == NIL)
        return;

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

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

    int N;
    in >> N;

    initTreap();

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

        if (t == 1)
            insert(Root, x, rand() % 100000000);
        else if (t == 2)
            erase(Root, x);
        else
            out << find(Root, x) << "\n";
    }

    return 0;
}