Cod sursa(job #1590438)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 5 februarie 2016 04:15:03
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.44 kb
#include <bits/stdc++.h>

#define left ((pz<<1)|1)
#define right ((pz+1)<<1)
#define dad  ((pz-1)>>1)

using namespace std;

template <class T> class Heap{
private:
    vector<T> h;
    size_t Size;
public:
    Heap(){
    }
    void Resize(int k){
        Size = k;
        h.resize(k);
    }
    int Down_Heap(int pz){ /// aka Heapify
        T aux = h[pz];
        while( (left < Size && h[left] > aux) || (right < Size && h[right] > aux) ){
            if(left < Size && right < Size && h[left] >= h[right]){
                h[pz] = h[left];pz = left;continue;
            }
            if(right < Size && left < Size && h[right] >= h[left]){
                h[pz] = h[right];pz = right;continue;
            }
            if(left < Size){
                h[pz] = h[left];pz = left;continue;
            }
            h[pz] = h[right];pz = right;
        }
        h[pz] = aux;
        return pz;
    }
    int Up_Heap(int pz){
        T aux = h[pz];
        while(pz && h[dad] < aux){
            h[pz] = h[dad];
            pz = dad;
        }
        h[pz] = aux;
        return pz;
    }
    void Pop(){
        int pz = Size;
        swap(h[0],h[--Size]);
        h.pop_back();
        Down_Heap(0);
    }
    void Insert(T elem){
        if(Empty()) Resize(1);
        h[Size++] = elem;
        Up_Heap(Size - 1);
    }
    void Make_Heap(vector<T> a){
        Resize(a.size());
        for(int i = 0; i < a.size(); ++i)
            h[i] = a[i];
        for(int i = Size/2 ; i >= 0; --i)
            Down_Heap(i);
    }
    void Delete(int pz){
        swap(h[pz],h[--Size]);
        h.pop_back();
        Up_Heap(pz);
        Down_Heap(pz);
    }
    T Top(){
        return h[0];
    }
    bool Empty(){
        return Size == 0;
    }
    size_t Sizeof(){
        return Size;
    }
    void Print(){
        for(int i = 0; i < Size; ++i)
            printf("%d ",h[i]);
    }
};
vector<int> v,s;
vector<vector<int> > a;
Heap<int> T;
Heap<pair<int,int> > KHeap;
int N,M,K;

void Heap_Sort(){
    scanf("%d",&N);
    v.resize(N);
    for(int i = 0; i < N; ++i)
        scanf("%d",&v[i]);
    T.Make_Heap(v);
    int pz = N-1;
    while(!T.Empty()){
        v[pz--] = T.Top();
        T.Pop();
    }
    for(auto it : v)
        printf("%d ",it);
}



int main()
{
    freopen("algsort.in","r",stdin);
    freopen("algsort.out","w",stdout);

    Heap_Sort();

    return 0;
}