Cod sursa(job #1507606)

Utilizator retrogradLucian Bicsi retrograd Data 21 octombrie 2015 19:20:34
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.08 kb
#include <bits/stdc++.h>

using namespace std;

struct TreapNode {
    //Needed for Treap functioning
    int key, priority, l, r;

    //Extra data (augmentation)
    int sz;
};
TreapNode T[500000];
int nodes, root = 0;

struct Treap {

    void split(int x, int key, int &l, int &r) {
        if(x == 0)
            l = r = 0;
        else if(key < T[x].key)
            split(T[x].l, key, l, T[x].l), r = x;
        else
            split(T[x].r, key, T[x].r, r), l = x;
    }

    void join(int &to, int l, int r) {
        if(!l)
            to = r;
        else if(!r)
            to = l;
        else if(T[l].priority > T[r].priority)
            join(T[l].r, T[l].r, r), to = l;
        else
            join(T[r].l, l, T[r].l), to = r;
    }

    void ins(int &to, int what) {
        if(to == 0) to = what;
        else if(T[to].priority > T[what].priority) {
            if(T[to].key > T[what].key)
                ins(T[to].l, what);
            else
                ins(T[to].r, what);
        } else {
            split(to, T[what].key, T[what].l, T[what].r);
            to = what;
        }
    }

    void insert(int &to, int key) {
        if(find(to, key)) return;

        ++nodes;
        T[nodes].key = key;
        T[nodes].priority = rand();
        ins(to, nodes);
    }

    void erase(int &x, int key) {
        if(x == 0) return;
        if(T[x].key == key) join(x, T[x].l, T[x].r);
        else if(key < T[x].key)
            erase(T[x].l, key);
        else
            erase(T[x].r, key);
    }

    bool find(int &x, int key) {
        if(x == 0) return false;
        if(T[x].key == key) return true;
        if(key < T[x].key) return find(T[x].l, key);
        return find(T[x].r, key);
    }

};

Treap Tr;

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

    int n, t, a;
    fin>>n;
    while(n--) {
        fin>>t>>a;
        if(t == 1) Tr.insert(root, a);
        if(t == 2) Tr.erase(root, a);
        if(t == 3) fout<<Tr.find(root, a)<<'\n';
    }
    return 0;
}