Cod sursa(job #656853)

Utilizator d.andreiDiaconeasa Andrei d.andrei Data 5 ianuarie 2012 13:50:18
Problema Hashuri Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 2.13 kb
//treapuri
#include <cstdio>
#include <ctime>
#include <cstdlib>

#define file_in "hashuri.in"
#define file_out "hashuri.out"


struct nod{
    int val,h;
    nod * st, * dr;
    nod(){}
    nod(int val, int h, nod * st, nod * dr){
        this->val=val;
        this->h=h;
        this->st=st;
		this->dr=dr;
    }
}*R, *nil;

int T,x,tip;


void init(nod *& R){
    srand(unsigned(time(0)));
    R=nil=new nod(0,0,NULL,NULL);
}

void rotst(nod *& c){
	nod * v=c->st;
	c->st=v->dr;
	v->dr=c;
	c=v;
}

void rotdr(nod *& c){
	nod * v=c->dr;
	c->dr=v->st;
	v->st=c;
	c=v;
}
	

void balance(nod *& c){
	
	if (c->st->h>c->h)
		rotst(c);
	else
	if (c->dr->h>c->h)
		rotdr(c);
}

void inserare(nod *& c, int x,int h){
	
	if (c==nil){
		c=new nod(x,h,nil,nil);
		return;
	}
	else
		if (c->val>x)
			inserare(c->st,x,h);
		else
			inserare(c->dr,x,h);
	balance(c);	
}
		
	
	
int cautare(nod *& c, int x){
	
	if (c==nil)
		return 0;
	if (c->val==x)
		return 1;
	if (c->val>x)
		return cautare(c->st,x);
	else
		return cautare(c->dr,x);
}

void stergere(nod *& c, int x){
	
	if (c==nil)
		return ;
	
	if (c->val==x){
		if (c->st==nil && c->dr==nil){
			delete c;
			c=nil;
		}
		else
		if (c->st->h>c->dr->h)
            rotst(c);
        else
			rotdr(c);
		stergere(c,x);
	}
	else
	if (c->val>x)
		stergere(c->st,x);
	else
		stergere(c->dr,x);
}

#define D 8192
char g_buf[D];
int g_p=D-1;


inline int get()
{

	int x=0;
	while ((g_buf[g_p]<'0' || g_buf[g_p]>'9'))
		if (++g_p==D) fread(g_buf,1,D,stdin),g_p=0;
	while (g_buf[g_p]>='0' && g_buf[g_p]<='9'){
		x=x*10+g_buf[g_p]-'0';
		if (++g_p==D) fread(g_buf,1,D,stdin),g_p=0;
	}
	return x;
}
		

int main(){
	
	freopen(file_in,"r",stdin);
	freopen(file_out,"w",stdout);
	
    init(R);
	
	T=get();
	
	while(T--){
		
		tip=get();
		x=get();
		
		if (tip==1){
			//inserare
			if (!cautare(R,x))
			inserare(R,x,rand()+1);
		}
		else
		if (tip==3){
			//cautare
			printf("%d\n", cautare(R,x));
		}
		else{
			//stregere
			if (cautare(R,x));
			stergere(R,x);
		}
	}
	
	return 0;
	
}