Pagini recente » Cod sursa (job #528102) | Cod sursa (job #2524303) | Cod sursa (job #2818065) | Cod sursa (job #629348) | Cod sursa (job #1200891)
#include<fstream>
using namespace std;
ifstream f("hashuri.in");
ofstream o("hashuri.out");
struct dat{
int val,h,def;
dat *dr,*st;
dat(){
val=h=def=0;
dr=st=NULL;
}
};
//typedef dat *lda;
int n;
dat *head=NULL;
dat *hight(dat *v){
if(v->dr!=0 && v->st!=0){
v->h = max(v->dr->h,v->st->h)+1;
v->def = v->dr->h - v->st->h;
}else if(v->dr!=0 || v->st!=0){
if(v->dr!=0){
v->h = v->dr->h+1;
v->def = v->dr->h;
}else{
v->h = v->st->h+1;
v->def = -v->st->h;
}
}else{
v->h = 0;
v->def = 0;
}
return v;
}
dat *rotleft(dat *v){
dat *x = v->dr;
v->dr = x->st;
x->st = v;
v = hight(v);
x = hight(x);
return x;
}
dat *rotright(dat *v){
dat *x = v->st;
v->st = x->dr;
x->dr = v;
v = hight(v);
x = hight(x);
return x;
}
dat *echilibru(dat *v){
v = hight(v);
if(v->def==2){
if(v->dr->def>=0)v = rotleft(v);
else{
v->dr = rotright(v->dr);
v = rotleft(v);
}
}
if(v->def==-2){
if(v->st->def<=0)v = rotright(v);
else {
v->st = rotleft(v->st);
v = rotright(v);
}
}
return v;
}
dat *adauga(dat *v, int x){
if(v==NULL){
dat *p = new dat;
p->val = x;
p->h = 0;
p->def = 0;
v=p;
return v;
}
if(v->val<=x)v->st = adauga(v->st,x);
else v->dr = adauga(v->dr,x);
v = echilibru(v);
return v;
}
int cautamax(dat *nod){
if(nod->st==NULL)return nod->val;
return cautamax(nod->st);
}
int cautamin(dat *nod){
if(nod->dr==NULL)return nod->val;
return cautamin(nod->dr);
}
int cauta(int x,dat *v){
if(v==NULL)return 0;
if(v->val == x)return 1;
if(v->val<=x) return cauta(x,v->st);
else return cauta(x,v->dr);
}
dat *sterge(int x,dat *v){
if(v==NULL)return 0;
if(v->val == x){
if(v->dr==0 && v->st==0){
return 0;
}else if(v->dr==0 || v->st==0){
if(v->dr==0)return v->st;
else return v->dr;
}else{
dat *p;
for(p=v->dr;p->st!=NULL;p=p->st);
v->val = p->val;
v->dr = sterge(p->val,v->dr);
return echilibru(v);
}
}
else
if(v->val<=x) v->st = sterge(x,v->st);
else v->dr = sterge(x,v->dr);
return echilibru(v);
}
int main(){
f>>n;
int x,y;
for(int i=1;i<=n;i++){
f>>x>>y;
switch(x){
case 1:head = adauga(head,y);break;
case 2:head = sterge(y,head);break;
case 3:o<<cauta(y,head)<<endl;break;
}
}
}