Cod sursa(job #1207197)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 12 iulie 2014 15:07:35
Problema Sortare prin comparare Scor 60
Compilator cpp Status done
Runda Arhiva educationala Marime 2.35 kb
#include <cstdio>
#include <algorithm>

using namespace std;

class AVL{
public:
    int value;
    unsigned short height;
    AVL *st,*dr;
    AVL(int value,int height,AVL *st,AVL *dr){
        this->value = value;
        this->height = height;
        this->st = st;
        this->dr = dr;
    }
}*root,*nil;

inline int maxi(unsigned short s1,unsigned short s2)
{
    if( s1 < s2 ) return s2;
    return s1;
}

void init(){
    root = nil = new AVL(0,0,NULL,NULL);
}

void Rotate_left(AVL *&n)
{
    AVL *aux = n->st;
    n->st = aux->dr;
    n -> height = maxi(n->st->height,n->dr->height)+1;
    aux->dr = n;
    aux->height = maxi(aux->st->height,aux->dr->height) + 1;
    n = aux;
}
void Rotate_right(AVL *&n)
{
    AVL *aux = n->dr;

    n->dr = aux->st;
    n->height = maxi(n->st->height,n->dr->height)+1;
    aux->st = n;
    aux->height = maxi(aux->st->height,aux->dr->height) + 1;
    n = aux;
}

void Balance(AVL *&n)
{
    if(n->st->height > n->dr->height + 1)
    {
        ///if(n->st->st->height < n->st->dr->height)
           /// Rotate_right(n->st);
        Rotate_left(n);
    }
    else
        if(n->st->height + 1 < n->dr->height )
        {
            ///if(n->dr->dr->height < n->dr->st->height)
               /// Rotate_left(n->dr);
            Rotate_right(n);
        }
    n->height = maxi(n->st->height,n->dr->height) + 1;
}

void Delete(int value,AVL *&n)
{
    if(n == nil) return;
    if(n->value > value)
        Delete(value,n->st);
    else
        if(n->value < value)
            Delete(value,n->dr);
        else
            if(n->st == nil && n->dr == nil)
            {
                delete n; n = nil;
                return;
            }
}

void Insert(int value,AVL *&n)
{
    if(n == nil){
        n = new AVL(value,1,nil,nil);
        return;
    }
    if(n->value > value)
        Insert(value,n->st);
    else
        Insert(value,n->dr);
    Balance(n);
}

void srd(AVL *nod){
    if(nod == nil) return;
    srd(nod->st);
    printf("%d ",nod->value);
    srd(nod->dr);

}

int main()
{
    init();
    int N,x;
    freopen("algsort.in","r",stdin);
    freopen("algsort.out","w",stdout);
    scanf("%d",&N);
    for(int i = 1; i <= N; ++i)
    {
        scanf("%d",&x);
        Insert(x,root);
    }
    srd(root);
    return 0;
}