Cod sursa(job #2073632)

Utilizator Andreiii500Andrei Puiu Andreiii500 Data 23 noiembrie 2017 14:37:03
Problema Sortare prin comparare Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.75 kb
#include<iostream>
#include<fstream>
#include<iomanip>
using namespace std;

ifstream in("algsort.in");
ofstream out("algsort.out");

const int N = 500000;
const int INF = (1<<31)-1;

struct min_heap{
    int values[N+1];
    int length = 0;


    int get_min(){ /// Returns the minimal value in the heap
        return values[1];
    }

    void push(int x){ /// Pushes value 'x' into the heap
        if(length == N)
        {
            cout<<"Error! Heap is full\n";
            return;
        }

        /// Insert 'x' into the heap
        values[++length] = x;

        /// Repair the heap
        int pos = length;
        while(pos != 1 && values[pos] < values[pos/2])
        {
            swap(values[pos], values[pos/2]); /// Swap the father and son
            pos /= 2; /// Ascend to its father
        }
    }

    void pop(){
        if(length < 1)
        {
            cout<<"Error! Can't pop from NULL heap\n";
            return;
        }

        /// Remove the heap's root value
        values[1] = values[length];
        --length;

        /// Repair the heap
        int pos = 1;
        while(1){
            int father, leftSon, rightSon;

            father = values[pos]; /// Father value
            if(2*pos > length) /// Left son value
                leftSon = INF;
            else
                leftSon = values[2*pos];
            if(2*pos + 1 > length) /// Right son value
                rightSon = INF;
            else
                rightSon = values[2*pos + 1];

            if(father > leftSon || father > rightSon) /// We need to swap the father with one of its sons
            {
                if(leftSon < rightSon) /// Swap it with the left son
                {
                    swap(values[pos], values[pos*2]);
                    pos = pos*2;
                }
                else /// Swap it with the right son
                {
                    swap(values[pos], values[pos*2 + 1]);
                    pos = pos*2 + 1;
                }
            }
            else /// We have finished repairing the tree!
            {
                break;
            }
        }
    }

    void print(){
        int power = 1, cnt = 1;
        while(cnt <= length)
        {
            for(int i=1; i<=power && cnt <= length; ++i)
                cout<<setw(4)<<values[cnt++];
            cout<<"\n";
            power <<= 1;
        }
        cout<<"\n";
    }
};

int main()
{
    min_heap h;
    int n;

    in>>n;
    for(int i=0; i<n; ++i)
    {
        int x;
        in>>x;
        h.push(x);
    }

    for(int i=0; i<n; ++i)
    {
        cout<<h.get_min()<<" ";
        //h.print();
        h.pop();
    }

    return 0;
}