Cod sursa(job #812971)

Utilizator a_h1926Heidelbacher Andrei a_h1926 Data 14 noiembrie 2012 19:33:26
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.74 kb
#include <cstdio>
#include <cstdlib>
#include <ctime>

using namespace std;

const int oo = 0x3f3f3f3f;

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

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

Treap *T, *NIL;

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

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

inline void RotRight(Treap* &Node) {
    Treap *Aux = Node->Left;
    Node->Left = Node->Left->Right;
    Aux->Right = Node;
    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->Priority > Node->Right->Priority)
            RotRight(Node);
        else
            RotLeft(Node);
        Erase(Node, Key);
    }
    else {
        if (Key < Node->Key)
            Erase(Node->Left, Key);
        else
            Erase(Node->Right, Key);
    }
}

inline 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);
}

inline Treap* Merge(Treap* &T1, Treap* &T2) {
    int Key;
    for (Treap* Node = T1; Node != NIL; Node = Node->Right)
        Key = Node->Key;
    Treap* Root = new Treap(Key, 0, T1, T2);
    Erase(Root, Key);
    return Root;
}

inline void Split(Treap* &Root, int Key, Treap* &T1, Treap* &T2) {
    Insert(Root, Key, oo);
    T1 = Root->Left, T2 = Root->Right;
    delete Root; Root = NIL;
}

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