Cod sursa(job #1456812)

Utilizator fluture.godlikeGafton Mihnea Alexandru fluture.godlike Data 1 iulie 2015 23:34:24
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <cstdio>
#include <algorithm>
#define NMAX 500007
using namespace std;
FILE *fin, *fout;
int n, h[NMAX], temp;
int father(int x)
{
    return x/2;
}
int left(int x)
{
    return x*2;
}
int right(int x)
{
    return x*2+1;
}
int top()
{
    return h[1];
}
void upheap(int x)
{
    while(father(x)>0 && h[x] < h[father(x)])
    {
        swap(h[x], h[father(x)]);
        x = father(x);
    }
}
void downheap(int x)
{
    int best = x;
    if(left(x) <= h[0]) if(h[left(x)] < h[best]) best = left(x);
    if(right(x) <= h[0]) if(h[right(x)] < h[best]) best = right(x);
    while(best != x)
    {
        swap(h[x], h[best]);
        x = best;
        if(left(x) <= h[0]) if(h[left(x)] < h[best]) best = left(x);
        if(right(x) <= h[0]) if(h[right(x)] < h[best]) best = right(x);
    }
}
void hinsert(int val)
{
    h[0]++;
    h[h[0]] = val;
    upheap(h[0]);
}
void herase(int x)
{
    swap(h[h[0]], h[x]);
    h[0]--;
    downheap(x);
}
int main()
{
    fin = freopen("algsort.in", "r", stdin);
    fout = freopen("algsort.out", "w", stdout);
    scanf("%d", &n);
    for(int i = 1; i<= n; i++)
    {
        scanf("%d", &temp);
        hinsert(temp);
    }
    for(int i = 1; i<= n; i++)
    {
        printf("%d ", top());
        herase(1);
    }
    printf("\n");
    fclose(fin);
    fclose(fout);
    return 0;
}