Cod sursa(job #1218151)

Utilizator ArchazeyBaltatu Andrei-Mircea Archazey Data 9 august 2014 18:09:24
Problema Hashuri Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.5 kb
#include<fstream>
using namespace std;

struct cell
{
    int val;
    cell *legst,*legdr;
    cell()
    {
        legst=legdr=NULL;
    }
};

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

int n,nr;
cell *root,*p,*q,*tata,*aux;

inline void ROTATER(cell *t,cell *act,cell *fiu)
{
    if (t->legst==act) t->legst=fiu;
    if (t->legdr==act) t->legdr=fiu;
    aux=fiu->legdr;
    fiu->legdr=act;
    act->legst=aux;
}

inline void ROTATES(cell *t,cell *act,cell *fiu)
{
    if (t->legst==act) t->legst=fiu;
    if (t->legdr==act) t->legdr=fiu;
    aux=fiu->legst;
    fiu->legst=act;
    act->legdr=aux;
}

inline void ADAUGA(cell *c,int x,cell *t)
{
    if (x<c->val)
        {
            if (c->legst==NULL)
                {
                    p=new cell;
                    c->legst=p;
                    p->val=x;
                    nr++;
                }
            else {ADAUGA(c->legst,x,c);if (c!=root) ROTATES(t,c,c->legst);}
        }
    if (x>c->val)
        {

            if (c->legdr==NULL)
                {
                    p=new cell;
                    c->legdr=p;
                    p->val=x;
                    nr++;
                }
            else {ADAUGA(c->legdr,x,c);if (c!=root) ROTATER(t,c,c->legdr);}
        }

}

inline void STERGE(cell *c,int x,int nr)
{
    if (x==c->val)
        {
            p=c->legst;
            q=c->legdr;
            while (q || p)
                {
                    if (q) {ROTATER(tata,c,q);tata=q;}
                    if (p) {ROTATES(tata,c,p);tata=p;}
                }
            if (tata->legst==c) tata->legst=NULL;
            if (tata->legdr==c) tata->legdr=NULL;
            nr--;
        }
    if (x<c->val && c->legst!=NULL) {tata=c;STERGE(c->legst,x,nr+1);}
    if (x>c->val && c->legdr!=NULL) {tata=c;STERGE(c->legdr,x,nr+1);}
}

inline bool FIND(cell *c,int x)
{
    if (x==c->val) return 1;
    if (x<c->val && c->legst!=NULL) return FIND(c->legst,x);
    if (x>c->val && c->legdr!=NULL) return FIND(c->legdr,x);
    return 0;
}

int main()
{
    int ok,x;
    fin>>n;
    while (n--)
        {
            fin>>ok>>x;
            if (ok==1)
                {
                    if (nr==0)
                        {nr++;root=new cell;root->val=x;}
                    else ADAUGA(root,x,root);
                }
            if (ok==2 && nr) STERGE(root,x,0);
            if (ok==3 && nr) fout<<FIND(root,x)<<"\n";
        }
    return 0;
}