Cod sursa(job #1249931)

Utilizator okros_alexandruOkros Alexandru okros_alexandru Data 27 octombrie 2014 17:42:41
Problema Sortare prin comparare Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.46 kb
#include <fstream>

#define Bmax (1 << 14)
#define Nmax 500100
#define digit(x) ('0' <= x && x <= '9')

using namespace std;

class HEAP {

    #define Root 1
    #define Father (Node >> 1)
    #define leftSon (Node << 1)
    #define rightSon ((Node << 1) | 1)
    #define compare(a, b) (Heap[a] < Heap[b])

    private:
        int top, Heap[Nmax];

    public:

        HEAP() {

            top = 0;

        }

        void insert(int Value) {

            Heap[++top] = Value;
            up(top);

        }

        void pop() {

            Heap[1] = Heap[top--];
            down(1);

        }

        int front() {

            return Heap[1];


        }

        int size() {

            return top;

        }

    private:

        void up(int Node) {

            while(Node != Root && compare(Node, Father)) {
                swap(Heap[Node], Heap[Father]);
                Node = Father;
                }

        }

        void down(int Node) {

            int Son;

            do {

                Son = 0;

                if(leftSon <= size()) {

                    Son = leftSon;
                    if(rightSon <= size() && compare(rightSon, leftSon))
                        Son = rightSon;

                    if(compare(Node, Son))
                        Son = 0;

                    }

                if(Son != 0) {
                    swap(Heap[Node], Heap[Son]);
                    Node = Son;
                    }

            } while(Son != 0);

        }

};

char Buffer[Bmax];
int bufferIndex = Bmax - 1;

HEAP H;
int N;

int readBuffer(ifstream & in, int & X) {

    do {

        if(++bufferIndex == Bmax)
            bufferIndex = 0, in.read(Buffer, Bmax);

    } while(!digit(Buffer[bufferIndex]));

    for(X = 0; digit(Buffer[bufferIndex]); ) {

        X = X * 10 + Buffer[bufferIndex] - '0';

        if(++bufferIndex == Bmax)
            bufferIndex = 0, in.read(Buffer, Bmax);

    }

}
void Read() {

    int i, x;

    ifstream in("algsort.in");
    readBuffer(in, N);

    for(i = 1; i <= N; i++) {
        readBuffer(in, x);
        H.insert(x);
        }

    in.close();

}
void Write() {

    ofstream out("algsort.out");

    for(int i = 1; i <= N; i++) {
        out << H.front() << ' ';
        H.pop();
        }

    out.close();

}
int main() {

    Read();
    Write();

    return 0;

}