Cod sursa(job #2198719)

Utilizator AurelGabrielAurel Gabriel AurelGabriel Data 25 aprilie 2018 10:28:59
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <vector>
using namespace std;

typedef unsigned  long int ulong;

ulong n;

template<typename T>
class heap{
public:
    heap() {}
    inline T getMin() const { return heapA[0];}
    inline void push(T t) { heapA.push_back(t); int i = heapA.size()-1; while(i&&heapA[parent(i)] > heapA[i]) swap(heapA[parent(i)], heapA[i]), i = parent(i); }
    inline ulong left(ulong index) const { return 2*index+1; }
    inline ulong right(ulong index) const { return 2*index+2; }
    inline ulong parent(ulong index) const { return (index-1)/2; }
    void minHeapify(ulong index){ int mn = index;
                                  if(left(index)  <  heapA.size() && heapA[left (index)]<heapA[mn]) mn=left (index);
                                  if(right(index) <  heapA.size() && heapA[right(index)]<heapA[mn]) mn=right(index);
                                  if(mn!=index) swap(heapA[mn], heapA[index]), minHeapify(mn);}
    void popMin() { heapA[0] = heapA[heapA.size()-1]; heapA.pop_back(); minHeapify(0); }
    ~heap() {}
private:
    vector<T> heapA;
};

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

    heap<ulong> h;

    f >> n;
    for(ulong i = 0; i < n; i++)
    {
        ulong u;
        f >> u;
        h.push(u);
    }

    for(ulong i = 0; i < n; i++)
    {
        g << h.getMin() << ' ';
        h.popMin();
    }

    return 0;
}