Cod sursa(job #1947267)

Utilizator andreigasparoviciAndrei Gasparovici andreigasparovici Data 30 martie 2017 21:11:07
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.43 kb
#include <cstdio>
#define MAXN 500001
#define INFINIT 0x3f3f3f3f

int n, m, heap[MAXN];

void swap(int &x,int &y)
{
    int z = x;
    x = y;
    y = z;
}

void heap_update(int n)
{
    if(heap[n>>1] > heap[n])
    {
        swap(heap[n>>1],heap[n]);
        heap_update(n>>1);
    }
}

void heap_insert(int x)
{
    ++n;
    heap[n]=x;
    heap_update(n);
}

void heap_resolve(int nod)
{

    if(((nod<<1) <=n && heap[nod] <= heap[(nod<<1)]) \
        && ((nod<<1)+1 <= n && heap[nod] <= heap[(nod<<1)+1]))
        return;

    int left = INFINIT, right = INFINIT;

    if((nod<<1) <= n)
        left = heap[(nod<<1)];
    if((nod<<1) +1 <= n)
        right = heap[(nod<<1) + 1];
    if(left == right)
        return;
    if(left < right && heap[(nod<<1)] < heap[nod] && (nod<<1) <=n)
    {
        swap(heap[nod],heap[(nod<<1)]);
        heap_resolve((nod<<1));
    }
    else if(heap[(nod<<1)+1] < heap[nod] && (nod<<1) +1 <=n)
    {
        swap(heap[nod],heap[(nod<<1)+1]);
        heap_resolve((nod<<1)+1);
    }
}

void heap_remove(int nod)
{
    swap(heap[nod],heap[n]);
    n--;
    heap_resolve(nod);
}

void citire()
{
    scanf("%d ",&m);
    for(int i=1;i<=m;i++)
    {
        int x;
        scanf("%d",&x);
        heap_insert(x);
    }
    for(int i=1;i<=m;i++)
    {
        printf("%d ",heap[1]);
        heap_remove(1);
    }
}

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

    citire();

    return 0;
}