Mai intai trebuie sa te autentifici.

Cod sursa(job #1971372)

Utilizator Andrei1998Andrei Constantinescu Andrei1998 Data 20 aprilie 2017 12:53:48
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.55 kb
#include <fstream>
#include <utility>
#include <chrono>
#include <random>

//12:36
using namespace std;
using namespace chrono;

struct Treap {
    int key, pr;
    Treap *left, *right;
} *root, *nil;

pair <Treap*, Treap*> split(Treap *t, int key) {
    if (t == nil)
        return make_pair(nil, nil);

    pair <Treap*, Treap*> aux;
    if (key < t -> key) {
        aux = split(t -> left, key);
        t -> left = aux.second;
        aux.second = t;
    }
    else {
        aux = split(t -> right, key);
        t -> right = aux.first;
        aux.first = t;
    }

    return aux;
}

Treap* join(Treap *l, Treap *r) {
    if (l == nil)
        return r;
    if (r == nil)
        return l;

    if (l -> pr > r -> pr) {
        l -> right = join(l -> right, r);
        return l;
    }
    else {
        r -> left = join(l, r -> left);
        return r;
    }
}

void insert(Treap* &t, int key, int pr) {
    if (pr > t -> pr) {
        auto aux = split(t, key);
        t = new Treap;
        t -> key = key;
        t -> pr = pr;
        t -> left = aux.first;
        t -> right = aux.second;
        return ;
    }
    else if (key <= t -> key)
        insert(t -> left, key, pr);
    else
        insert(t -> right, key, pr);
}

void erase(Treap* &t, int key) {
    if (t -> key == key) {
        Treap *aux = t;
        t = join(t -> left, t -> right);
        delete aux;
        return ;
    }
    else if (key < t -> key)
        erase(t -> left, key);
    else
        erase(t -> right, key);
}

bool find(Treap *t, int key) {
    if (t == nil)
        return false;
    else if (t -> key == key)
        return true;
    else if (key < t -> key)
        return find(t -> left, key);
    else
        return find(t -> right, key);
}

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

    auto now = system_clock :: now();
    auto d = now.time_since_epoch();
    mt19937 gen(duration_cast <milliseconds>(d).count());
    uniform_int_distribution <int> dist(1, (1 << 29));

    nil = new Treap;
    nil -> key = nil -> pr = -1;
    nil -> left = nil -> right = nil;
    root = nil;

    int M = 0;
    cin >> M;

    for (int i = 1; i <= M; ++ i) {
        int type, x;
        cin >> type >> x;
        if (type == 1)
            insert(root, x, dist(gen));
        else if (type == 2) {
            if (find(root, x))
                erase(root, x);
        }
        else
            cout << find(root, x) << '\n';
    }

    return 0;
}