Cod sursa(job #2270100)

Utilizator PredescuSebastianIonPredescu Sebastian Ion PredescuSebastianIon Data 27 octombrie 2018 09:11:02
Problema Sortare prin comparare Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <bits/stdc++.h>

using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int n,i,x,h[500003],sol[500003];
void heapup(int x)
{
    if(x>1)
    {
        if(h[x]>h[x/2])
        {
            swap(h[x],h[x/2]);
            heapup(x/2);
        }
    }
}
void heapdown(int x,int n)
{
    int st,dr;
    if(x*2<=n)
    {
        st=h[x*2];
        if(x*2+1<=n)dr=h[x*2+1];
        else dr=st-1;

        if(max(st,dr)>h[x])
        {
            if(st>dr)
            {
                swap(h[x],h[2*x]);
                heapdown(2*x,n);
            }
            else
            {
                swap(h[x],h[2*x+1]);
                heapdown(2*x+1,n);
            }
        }
    }
}
int main()
{
    f>>n;
    for(i=1;i<=n;i++)
    {
        f>>x;
        h[i]=x;
        heapup(i);
    }
    int cn=n;
    for(i=1;i<=cn;i++)
    {
        sol[i]=h[1];
        swap(h[1],h[n]);
        n--;
        heapdown(1,n);
    }
    for(i=cn;i>=1;i--)
    {
        g<<sol[i]<<" ";
    }
    return 0;
}