Pagini recente » Cod sursa (job #2802951) | Cod sursa (job #805106) | Cod sursa (job #646311) | Cod sursa (job #1227441) | Cod sursa (job #652455)
Cod sursa(job #652455)
//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);
}
int main(){
freopen(file_in,"r",stdin);
freopen(file_out,"w",stdout);
init(R);
scanf("%d", &T);
while(T--){
scanf("%d %d", &tip, &x);
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;
}