Pagini recente » Cod sursa (job #1731018) | Cod sursa (job #1625260) | Cod sursa (job #1231011) | Cod sursa (job #2025480) | Cod sursa (job #1278696)
#include <cstdio>
struct nod
{
int x,h;
nod *st, *dr;
}*RAD,*NIL;
int n,v;
void init()
{
NIL = new nod;
NIL->h = 0;
NIL->st = NULL;
NIL->dr = NULL;
NIL->x = 0;
RAD = NIL;
}
void geth(nod *p)
{
if(p->st->h > p->dr->h)
p->h = p->st->h + 1;
else
p->h = p->dr->h + 1;
}
nod* LL(nod *p)
{
nod *q;
q = p->st;
p->st = q->dr;
q->dr = p;
geth(p);
geth(q);
return q;
}
nod* RR(nod *p)
{
nod *q;
q = p->dr;
p->dr = q->st;
q->st = p;
geth(p);
geth(q);
return q;
}
nod* balance(nod *p)
{
geth(p);
if(p->st->h > p->dr->h + 1)
{
if(p->st->dr->h > p->st->st->h)
p->st = RR(p->st);
p=LL(p);
}
if(p->dr->h > p->st->h + 1)
{
if(p->dr->st->h > p->dr->dr->h)
p->dr = LL(p->dr);
p=RR(p);
}
return p;
}
nod* inserare(nod *p, int x)
{
if(p!=NIL)
{
if(p->x > x)
p->st = inserare(p->st, x);
else
p->dr = inserare(p->dr, x);
}
else
{
nod *nou;
nou = new nod;
nou->x = x;
nou->h = 1;
nou->st = NIL;
nou->dr = NIL;
return nou;
}
return balance(p);
}
void afisare(nod *p)
{
if(p!= NIL)
{
afisare(p->st);
printf("%d ", p->x);
afisare(p->dr);
}
}
int main()
{
init();
freopen("algsort.in", "r", stdin);
freopen("algsort.out", "w", stdout);
scanf("%d ", &n);
for(int i = 0; i<n; i++)
{
scanf("%d ", &v);
RAD = inserare(RAD, v);
}
afisare(RAD);
}