Pagini recente » Cod sursa (job #2852206) | Cod sursa (job #2435349) | Cod sursa (job #2820230) | Cod sursa (job #878542) | Cod sursa (job #1200958)
#include<fstream>
using namespace std;
ifstream f("hashuri.in");
ofstream o("hashuri.out");
struct dat{
int val,h,def;
dat *dr,*st;
dat(){
val=0;
h=def=0;
dr=st=0;
}
};
//typedef dat *lda;
int n;
dat *head;
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==0){
dat *p = new dat;
p->val = x;
//v=p;
return p;
}
if(v->val==x)return v;
else 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==0)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==0)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!=0;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;
head=0;
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)<<"\n";break;
}
}
}