Cod sursa(job #1278694)

Utilizator claudiu.gatinaFMI Claudiu Gatina claudiu.gatina Data 29 noiembrie 2014 11:17:23
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.67 kb
#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);
    scanf("%d ", &n);
    for(int i = 0; i<n; i++)
    {
        scanf("%d ", &v);
            RAD = inserare(RAD, v);
    }
    afisare(RAD);
}