Cod sursa(job #894800)

Utilizator paulbotabota paul paulbota Data 26 februarie 2013 23:37:32
Problema Sortare prin comparare Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include <cstdio>
#define MAXN 500010


int h[2*MAXN+100],poz[MAXN],k,n;

void swap(int x,int y)
{
    int aux=h[x];
    h[x]=h[y];
    h[y]=aux;
    poz[h[x]]=x;
    poz[h[y]]=y;
}

void upheap(int i)
{
    while(i>1 && h[i/2]>h[i])
    {
        swap(i/2,i);
        i=i/2;
    }
}

void downheap(int i)
{
    int stg,dr,max=i;
    stg=2*i;
    dr=2*i+1;
    if(stg<=k && h[stg]<h[i])
        max=stg;
    if(dr<=k && h[dr]<h[max])
        max=dr;
    if(max!=i)
    {
        swap(max,i);
        downheap(max);
    }
}

void insert_heap(int val)
{
    h[++k]=val;
    poz[val]=k;
    upheap(k);
}

int extract_min()
{
    int min=h[1];
    swap(1,k);
    k--;
    poz[min]=0;
    downheap(1);
    return min;
}

int main()
{
    freopen("algsort.in","r",stdin);
    freopen("algsort.out","w",stdout);
    scanf("%d",&n);
    for(;n;n--)
    {
        int i;
        scanf("%d",&i);
        insert_heap(i);
    }
    while(k)
    {
        printf("%d ",extract_min());
    }
    printf("\n");
    return 0;
}