Cod sursa(job #1243699)

Utilizator AlexandruValeanuAlexandru Valeanu AlexandruValeanu Data 16 octombrie 2014 11:11:40
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>

using namespace std;

const int Nmax = 500000 + 1;

class MinHeap
{
public:

    MinHeap()
    {
        heap = vector<int>( 1, 0 );
        heapSize = 0;
    }

    void insertHeap( const int val )
    {
        heap.push_back( val );
        UpHeap( ++heapSize );
    }

    int eraseHeap()
    {
        int val = heap[1];

        heap[1] = heap.back();
        heap.pop_back();
        heapSize--;

        DownHeap( 1 );

        return val;
    }

private:

    vector<int> heap;
    int heapSize;

    void UpHeap( int nod )
    {
        while ( nod > 1 && heap[nod / 2] > heap[nod] )
        {
            swap( heap[nod / 2], heap[nod] );
            nod /= 2;
        }
    }

    void DownHeap( int nod )
    {
        while ( 2 * nod <= heapSize )
        {
            int pos = 2 * nod;

            if ( 2 * nod + 1 <= heapSize && heap[2 * nod + 1] < heap[2 * nod] )
                pos = 2 * nod + 1;

            if ( heap[nod] <= heap[pos] )
                break;

            swap( heap[nod], heap[pos] );

            nod = pos;
        }
    }
};

int main()
{
    ifstream in("algsort.in");
    ofstream out("algsort.out");

    int N, a;

    in >> N;

    MinHeap A;

    for ( int i = 1; i <= N; ++i )
    {
        in >> a;
        A.insertHeap( a );
    }

    for ( int i = 1; i <= N; ++i )
        out << A.eraseHeap() << " ";

    return 0;
}