Cod sursa(job #1496204)

Utilizator ZenusTudor Costin Razvan Zenus Data 4 octombrie 2015 16:16:04
Problema Hashuri Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.89 kb
#include <bits/stdc++.h>

using namespace std;

ifstream fin("hashuri.in");
ofstream fout("hashuri.out");

struct treap
{
    int p , x;
    treap *tl , *tr;

    treap(treap *h)
    {
        p = x = 0;
        tl = tr = h;
    }
};

treap *r , *nth;
int q , cx , t , ok;

void rl(treap *(&r))
{
    treap *aux = r -> tl;
    r -> tl = aux -> tr;
    aux -> tr = r;
    r = aux;
}

void rr(treap *(&r))
{
    treap *aux = r -> tr;
    r -> tr = aux -> tl;
    aux -> tl = r;
    r = aux;
}

void redo(treap *(&r))
{
    if (r -> tl -> p > r -> p) rl(r);
    else if (r -> tr -> p > r -> p) rr(r);
}

bool is(treap *r , int cx)
{
    if (r == nth) return false;
    if (r -> x == cx) return true;

    if (r -> x > cx) return is(r -> tl , cx);
    else return is(r -> tr , cx);
}

void add(treap *(&r) , int cx)
{
    if (r == nth)
    {
        r = new treap(nth);
        r -> x = cx;
        r -> p = rand() + 1;
        return ;
    }

    if (r -> x > cx)
    add(r -> tl , cx);
    else add(r -> tr , cx);

    redo(r);
}

void out(treap *(&r) , int cx)
{
    if (r == nth)
    return ;

    if (r -> x - cx)
    {
        if (r -> x > cx) out(r -> tl , cx);
        else out(r -> tr , cx);

        return ;
    }

    if (r -> tr == nth && r -> tl == nth)
    {
        delete r;
        return ;
    }

    if (r -> tl -> p > r -> tr -> p) rl(r);
    else rr(r);
    out(r , cx);
}

int main()
{

nth = new treap(NULL);
nth -> x = 0;
nth -> p = 0;

r = nth;

for (fin >> q ; q ; --q)
{
    fin >> t >> cx;
    ok = is(r , cx);

    if (t == 1)
    {
        if (ok) continue;
        add(r , cx);
        continue;
    }

    if (t == 2)
    {
        if (!ok) continue;
        out(r , cx);
        continue;
    }

    if (t == 3)
    (ok) ? fout << "1" << '\n' : fout << "0" << '\n';
}

return 0;
}