Cod sursa(job #1488716)

Utilizator chiriacandrei25Chiriac Andrei chiriacandrei25 Data 19 septembrie 2015 17:07:13
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.87 kb
#include <fstream>
#include <bits/stdc++.h>
#define VAL 123456789
#define mp make_pair

using namespace std;

struct T
{
    T *left, *right;
    int key,pr;
    T(int x)
    {
        key=x; pr=rand()%VAL; left=right=0;
    }
} *root = 0;

inline T *Merge(T *L, T *R)
{
    if(L==0) return R;
    if(R==0) return L;
    if(L->pr <= R->pr)
    {
        R->left=Merge(L,R->left); return R;
    }
    else
    {
        L->right=Merge(L->right,R); return L;
    }
}

inline pair <T*,T*> Split(T *node, int x)
{
    if(node==0) return mp((T *)0,(T *)0);
    if(x<node->key)
    {
        pair <T*,T*> spl=Split(node->left,x);
        node->left=spl.second;
        spl.second=node; return spl;
    }
    else
    {
        pair <T*,T*> spl=Split(node->right,x);
        node->right=spl.first;
        spl.first=node; return spl;
    }
}

inline T *Remove(T *node, int x)
{
    if(node==0) return 0;
    if(node->key<x) node->right=Remove(node->right,x);
    else
        if(node->key>x) node->left=Remove(node->left,x);
        else
        {
            T *aux=Merge(node->left,node->right);
            delete(node); node=aux;
        }
    return node;
}

inline bool Find(T *node, int x)
{
    if(node==0) return false;
    if(node->key>x) return Find(node->left,x);
    else
        if(node->key<x) return Find(node->right,x);
    return node;
}

inline T *Insert(int x)
{
    if(Find(root,x)) return root;
    pair <T*,T*> spl=Split(root,x);
    return Merge(Merge(spl.first,new T(x)) , spl.second);
}

int main()
{
    int T,tip,x;
    ifstream cin("hashuri.in");
    ofstream cout("hashuri.out");
    srand(time(0));
    cin>>T;
    while(T--)
    {
        cin>>tip>>x;
        if(tip==1) root=Insert(x);
        if(tip==2) root=Remove(root,x);
        if(tip==3) cout<<Find(root,x)<<"\n";
    }
    return 0;
}