Cod sursa(job #762095)

Utilizator mihai995mihai995 mihai995 Data 28 iunie 2012 17:43:19
Problema Heapuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 2.71 kb
#include <fstream>
#include <cstdlib>
using namespace std;

const int inf = 0x3f3f3f3f, N = 200005;

struct Nod
{
    int val, key;
    Nod *st, *dr;

    Nod()
    {
        val = key = 0;
        st = dr = NULL;
    }

    Nod(int _val, int _key, Nod* _st, Nod* _dr)
    {
        val = _val;
        key = _key;
        st = _st;
        dr = _dr;
    }
} *nil = new Nod(0, 0, NULL, NULL);

struct Treap
{
    Nod* root;

    Treap()
    {
        nil -> st = nil -> dr = nil;
        root = nil;
    }

    Nod* &search(Nod* &p, int x)
    {
        if (p -> val == x || p == nil)
            return p;

        return search(x < p -> val ? p -> st : p -> dr, x);
    }

    void rotate_left(Nod* &nod)
    {
        Nod* x = nod -> st;
        nod -> st = x -> dr;
        x -> dr = nod;
        nod = x;
    }

    void rotate_right(Nod* &nod)
    {
        Nod* x = nod -> dr;
        nod -> dr = x -> st;
        x -> st = nod;
        nod = x;
    }

    void balance(Nod* &nod)
    {
        if (nod -> st -> key > nod -> key)
            rotate_left(nod);
        if (nod -> dr -> key > nod -> key)
            rotate_right(nod);
    }

    void insert(Nod* &p, int x)
    {
        if (p == nil)
        {
            p = new Nod(x, rand() + 1, nil, nil);
            return;
        }

        insert(x <= p -> val? p -> st : p -> dr, x);

        balance(p);
    }

    void insert(int x)
    {
        insert(root, x);
    }

    void erase(Nod* &p)
    {
        if (p == nil)
            return;

        if (p -> st == nil || p -> dr == nil)
        {
            Nod* aux = p;
            p = p -> st == nil ? p -> dr : p -> st;
            delete aux;
            return;
        }

        if (p -> st -> key > p -> dr -> key)
        {
            rotate_left(p);
            erase(p -> dr);
        }
        else
        {
            rotate_right(p);
            erase(p -> st);
        }
        balance(p);
    }

    void erase(int x)
    {
        erase(search(root, x));
    }

    int minim()
    {
        Nod* p = root;

        while (p -> st != nil)
            p = p -> st;

        return p -> val;
    }
};

int v[N];

ifstream in("heapuri.in");
ofstream out("heapuri.out");

int main()
{
    int n, x;
    Treap T;

    in >> n;

    while (n--)
    {
        in >> x;

        if (x == 1)
        {
            in >> x;
            T.insert(x);
            v[++v[0]] = x;
            continue;
        }

        if (x == 2)
        {
            in >> x;
            T.erase(v[x]);
            continue;
        }

        out << T.minim() << "\n";
    }
    return 0;
}