Mai intai trebuie sa te autentifici.

Cod sursa(job #794802)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 7 octombrie 2012 00:26:34
Problema Hashuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.54 kb
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cassert>

using namespace std;

struct Treap {
    int Key, Priority;
    Treap *Left, *Right;

    Treap() {}
    Treap(int Key, int Priority, Treap *Left, Treap *Right) {
        this->Key = Key, this->Priority = Priority;
        this->Left = Left, this->Right = Right;
    }
};

Treap *R, *NIL;

void Initialize() {
    srand(time(0));
    R = NIL = new Treap(0, 0, NULL, NULL);
}

inline void RotLeft(Treap* &Node) {
    Treap *Aux = Node->Right;
    Aux->Left = Node;
    Node->Right = Node->Right->Left;
    Node = Aux;
}

inline void RotRight(Treap* &Node) {
    Treap *Aux = Node->Left;
    Aux->Right = Node;
    Node->Left = Node->Left->Right;
    Node = Aux;
}

inline void Balance(Treap* &Node) {
    if (Node->Left->Priority > Node->Priority)
        RotRight(Node);
    else if (Node->Right->Priority > Node->Priority)
        RotLeft(Node);
}

void Insert(Treap* &Node, int Key, int Priority) {
    if (Node == NIL) {
        Node = new Treap(Key, Priority, NIL, NIL);
        return;
    }
    if (Key <= Node->Key)
        Insert(Node->Left, Key, Priority);
    else
        Insert(Node->Right, Key, Priority);
    Balance(Node);
}

void Erase(Treap* &Node, int Key) {
    if (Node == NIL)
        return;
    if (Node->Key == Key) {
        if (Node->Left == NIL && Node->Right == NIL) {
            delete Node; Node = NIL;
        }
        else {
            if (Node->Left->Priority > Node->Right->Priority)
                RotRight(Node);
            else
                RotLeft(Node);
            Erase(Node, Key);
        }
    }
    else {
        if (Key < Node->Key)
            Erase(Node->Left, Key);
        if (Key > Node->Key)
            Erase(Node->Right, Key);
    }
}

int Search(Treap* &Node, int Key) {
    if (Node == NIL)
        return 0;
    if (Node->Key == Key)
        return 1;
    if (Key < Node->Key)
        return Search(Node->Left, Key);
    else
        return Search(Node->Right, Key);
}

int main() {
    Initialize();
    assert(freopen("hashuri.in", "r", stdin));
    assert(freopen("hashuri.out", "w", stdout));
    int M; assert(scanf("%d", &M) == 1);
    for (; M; --M) {
        int Type, X; assert(scanf("%d %d", &Type, &X) == 2);
        if (Type == 1)
            if (!Search(R, X))
                Insert(R, X, rand()+1);
        if (Type == 2)
            Erase(R, X);
        if (Type == 3)
            printf("%d\n", Search(R, X));
    }
    return 0;
}