Cod sursa(job #2071950)

Utilizator alexandruilieAlex Ilie alexandruilie Data 21 noiembrie 2017 10:45:08
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.98 kb
#include <fstream>
#include <climits>

#define inf LONG_MAX
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int h[500001],n,i,x,t;
void up(int p)
{
    if(p>1&&h[p/2]>h[p])
    {
        swap(h[p],h[p/2]);
        up(p/2);
    }
}
void add(int x)
{
    h[++t]=x;
    up(t);
}
void down(int p)
{
    if(p*2+1<=t&&(h[2*p]<h[p]||h[2*p+1]<h[p]))
    {
        if(h[2*p]<h[2*p+1])
        {
            swap(h[p],h[2*p]);
            down(2*p);
        }
        else
            {
            swap(h[p],h[2*p+1]);
            down(2*p+1);
        }
    }
    else if(2*p<=t&&h[p]>h[2*p])
        {
            swap(h[p],h[2*p]);
        }
}
void dell(int p)
{
    swap(h[p],h[t]);
    t--;
    up(p);
    down(p);
}
int main()
{
    f>>n;
     for(i=1;i<=n;i++) h[i]=inf;
    for(i=1;i<=n;i++)
    {
        f>>x;
        add(x);
    }
    while(t)
    {
        g<<h[1]<<' ';
        dell(1);
    }
    return 0;
}