Cod sursa(job #652206)

Utilizator d.andreiDiaconeasa Andrei d.andrei Data 23 decembrie 2011 13:47:01
Problema Hashuri Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#include <cstdio>

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

struct nod{
	
	int val;
	nod * st, *dr;
};

nod * v;

void insert(nod *& c, int x){
	
	if (c){
		
		if (c->val==x)
			return ;
		else
		if (c->val>x)
			insert(c->st,x);
		else
			insert(c->dr,x);
	}
	else{
		
		c=new nod;
		c->val=x;
		c->st=c->dr=0;
	}
}

int search(nod * c, int x){
	
	while(c){
		if (!c)
			return 0;
		if (c->val==x)
			return 1;
		else
			if (c->val<x)
				return search(c->dr,x);
			else
				return search(c->st,x);
	}
	
	return 0;
}

void doit(nod *&c, nod *& a){
    while(a->dr)
	doit(c,a->dr);
                nod * r;
		        c->val=a->val;
	 	        r=a;
		        a=a->st;
		        delete r;
}				


void erase(nod *& c, int x){
	
	nod * a;
	
	if (c){
		if (c->val==x)
			if (c->st==0 && c->dr==0){
				delete c;
				c=0;
			}
			else
			if (c->st==0){
                a=c->dr;
                delete c;
                c=a;
			}
			else
			if (c->dr==0){
                a=c->st;
                delete c;
                c=a;
			}	
			else{
				doit(c,c->st);
	            }
				
			else
		if (c->val<x)
            erase(c->dr,x);
		else
			erase(c->st,x);
	}
	else
		return ;
}


int main(){
	
	int Q,tip,x;
	
	freopen(file_in,"r",stdin);
	freopen(file_out,"w",stdout);
	
	scanf("%d", &Q);
	
	while(Q--){
		scanf("%d %d", &tip, &x);
		
		if (tip==1){
			//if (!search(v,x))
			insert(v,x);
		}
		else
		if (tip==2){
			//if (search(v,x))
				erase(v,x);
		}
		else{
			if (search(v,x))
		        printf("1\n");
		 	else
				printf("0\n");
		}
    }

return 0;

}