Cod sursa(job #1590437)

Utilizator gabrielinelusGabriel-Robert Inelus gabrielinelus Data 5 februarie 2016 03:08:03
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.66 kb
/**
*Question 7
    To remove an arbitrary element given its index, we will apply the following algorithm:
    |Delete( position )
    |
    |
*/
#include <bits/stdc++.h>

#define DIM 22613
#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;
    T top;
    size_t Size;
    T mINF = numeric_limits<T> :: min();
public:
    Heap(){
        top = 0;
    }
    void Resize(int k){
        Size = k;
        h.resize(2*k + 1);
        for(int i = k; i <= 2*k; ++i)
            h[i] = mINF;
    }
    int Down_Heap(int pz){ /// aka Heapify
        T aux = h[pz];
        while(h[left] > aux || h[right] > aux){
            if(h[left] >= h[right]){
                h[pz] = h[left];
                pz = left;
                continue;
            }
            if(h[right] >= h[left]){
                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[Size] = mINF;
        Down_Heap(0);
        h.pop_back();
        h.pop_back();
    }
    void Insert(T elem){
        if(Empty()) Resize(0);
        h.push_back(mINF);
        h.push_back(mINF);
        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[Size] = mINF;
        h.pop_back();
        h.pop_back();
        Up_Heap(pz);
        Down_Heap(pz);
    }
    T Top(){
        top = h[0];
        return top;
    }
    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;
Heap<int> T;
int N;

void Read(){
    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);
    Read();

    return 0;
}