Cod sursa(job #2036581)

Utilizator osiaccrCristian Osiac osiaccr Data 10 octombrie 2017 20:24:44
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.59 kb
#include <fstream>
#define DEF 500001

using namespace std;

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

int n, x;

bool _cmp (int &a, int &b) {
    return a > b;
}

class Heap {
public:
    void cut (int k);
    void push (int k);
    int top ();
private:
    int H[DEF];
    int h;
    void _swap (int a, int b);
    void _percolate (int k);
    void _sift (int k);
};

void Heap::_swap (int a, int b) {
    swap (H[a], H[b]);
}

void Heap::_sift (int k) {
    int son, ok = 1;
    while (son || ok) {
        ok = 0;
        son = 0;
        if (k * 2 <= h) {
            son = k * 2;
            if (k * 2 + 1 <= h && _cmp (H[2 * k], H[2 * k + 1])) {
                son = 2 * k + 1;
            }
            if (_cmp (H[son], H[k])) {
                son = 0;
            }
        }
        if (son) {
            _swap (k, son);
            k = son;
        }
    }

}

void Heap::_percolate (int k) {
    int c = k, p = k/2;
    while (p >= 1 && _cmp (H[p], H[c])) {
        _swap (c, p);
        c = p;
        p /= 2;
    }
}

void Heap::push (int k) {
    H[++h] = k;
    _percolate (h);
}

void Heap::cut (int k) {
    _swap (k, h);
    h--;

    if (k > 1 && _cmp (H[k / 2], H[k])) {
        _percolate (k);
    }
    else {
        _sift (k);
    }
}

int Heap::top () {
    return H[1];
}

Heap H;

int main  () {
    fin >> n;
    for (int i = 1; i <= n; i++) {
        fin >> x;
        H.push (x);
    }
    for (int i = 1; i <= n; i++) {
        fout << H.top () << " ";
        H.cut (1);
    }
}