Cod sursa(job #1462334)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 17 iulie 2015 19:55:12
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.79 kb
#include <bits/stdc++.h>

#define INF 0x3f3f3f3f

using namespace std;

class Treap{
public:
    int inf;
    short priority;
    Treap *st,*dr;
    Treap(){
        st = dr = NULL;
        inf = priority = 0;
    }
    Treap(const int &inf,const short &prio, Treap *st, Treap *dr){
        this->inf = inf;
        this->priority = prio;
        this->st = st;
        this->dr = dr;
    }
};

Treap *Null, *Root;

void Init(){
    srand((unsigned)time(0));
    Null = new Treap(0,-INF,NULL,NULL);
    Root = Null;
}

void Rotate_left(Treap *&T)
{
    Treap *aux = T->dr;
    T->dr = aux->st;
    aux->st = T;
    T = aux;
}

void Rotate_right(Treap *&T)
{
    Treap *aux = T->st;
    T->st = aux->dr;
    aux->dr = T;
    T = aux;
}

void Equilibrum(Treap *&T)
{
    if(T->priority < T->st->priority)
            Rotate_right(T);
    else
        if(T->priority < T->dr->priority)
            Rotate_left(T);
}

void Insert(Treap *&T,const int &info,const int &prio){
    if(T == Null){
        T = new Treap(info,prio,Null,Null);
        return;
    }

    if(T->inf > info)
        Insert(T->st,info,prio);
    else
        Insert(T->dr,info,prio);
    Equilibrum(T);
}

Treap* Find (Treap *&T, int value)
{
    if(T == Null || T->inf == value)
        return T;
    if(T->inf > value)
        return Find(T->st,value);
    return Find(T->dr,value);
}

void Delete(Treap *&T, const int &value)
{
    if(T->inf > value)
        Delete(T->st,value);
    else
        if(T->inf < value)
            Delete(T->dr,value);
        else
        {
            if(T->st == Null && T->dr == Null)
            {
                Treap *aux = T;
                T = Null;
                delete aux;
                return;
            }

            if(T->st->priority < T->dr->priority){
                Rotate_left(T);
                Delete(T->st,value);
            }else{
                    Rotate_right(T);
                    Delete(T->dr,value);
                }
        }
}

void Split(Treap *&T,Treap *&T1,Treap *&T2,int value)
{
    Insert(T,value,2*INF);
    T1 = T->st;
    T2 = T->dr;
    Treap *aux;
    aux = T;
    T = Null;
    delete aux;
}

void Join(Treap *&T,Treap *&T1, Treap *&T2)
{
    T = new Treap(2*INF,2*INF,T1,T2);
    Delete(T,2*INF);
    Treap *aux1,*aux2;
    T1 = T2 = Null;
}

void SRD(Treap *&T){
    if(T == Null)
        return;
    SRD(T->st);
    printf("%d ",T->inf);
    SRD(T->dr);
}

int main()
{
    Init();

    freopen("algsort.in","r",stdin);
    freopen("algsort.out","w",stdout);

    int N,x,pr;
    scanf("%d",&N);
    for(int i = 1; i <= N; ++i)
    {
        scanf("%d",&x);
        pr = rand();
        Insert(Root,x,pr);
    }
    SRD(Root);

    return 0;
}