Cod sursa(job #969600)

Utilizator okros_alexandruOkros Alexandru okros_alexandru Data 4 iulie 2013 19:10:37
Problema Sortare prin comparare Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 2.51 kb
#include <fstream>
#define nmax 500500
using namespace std;

int N, A[nmax];

#define bmax (1<<14)
char Buffer[bmax];
int Index = bmax-1;

inline void readBuffer(istream & in, int & X) {

	do {
		if(++Index == bmax)
			{Index=0;in.read(Buffer,bmax);}

	}while( Buffer[Index] < '0' || Buffer[Index] > '9' );

	for(X=0; Buffer[Index] >= '0' && Buffer[Index] <= '9';) {

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

		if(++Index == bmax)
			{Index=0;in.read(Buffer,bmax);}

		}

}
class heap {

	#define hmax nmax;
	#define father(node) (node>>1)
	#define leftSon(node) (node<<1)
	#define rightSon(node) ((node<<1)|1)
	#define compare(a, b) ( A[H[a]] < A[H[b]] )
	#define compareMin(a, b) compare(a, b)
	#define comapreMax(a, b) compare(b, a)

	public:
		int Top,H[nmax],Index[nmax];

	public:

		heap() {

			Top = 0;

			}

		void precolate(int Node) {

			while( Node > 1 && compareMin(Node, father(Node)) ) {

				swap(H[Node], H[father(Node)]);
				swap(Index[H[Node]], Index[H[father(Node)]]);
				Node = father(Node);

				}

		}

		void sift(int Node) {

			int Son;

			do {

				Son = 0;

				if( leftSon(Node) <= this -> size() ) {

					Son = leftSon(Node);

					if( rightSon(Node) <= this -> size() && compareMin(rightSon(Node), Son) )
						Son = rightSon(Node);

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

					}

				if( Son ) {

					swap(H[Node], H[Son]);
					swap(Index[H[Node]], Index[H[Son]]);
					Node = Son;

					}

			} while( Son );

		}

		void push(int Node, int Value) {

			H[ ++Top ] = Node;
			Index[Node] = Top;
			A[Node] = Value;
			this -> precolate(Top);

			}

		void pop() {

			H[1] = H[ Top-- ];
			this -> sift(1);

			}

		void update(int Node, int Value) {

			int Aux = A[Node];

			A[Node] = Value;

			if( Aux > A[Node] )
				this -> precolate( Index[Node] );
			else
				this -> sift( Index[Node] );

			}

		int size() {

			return Top;

			}

		bool empty() {

			return ( Top == 0);

			}

		int top() {

			return A[H[1]];

			}

};

heap Heap;

void Read() {

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

	for(int i = 1; i <= N; i++) {
        readBuffer(in, X);
        Heap.push(i, X);
        }

	in.close();

}
void Write() {

	ofstream out("algsort.out");

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

	out << '\n';
	out.close();

}
int main() {

	Read();
	Write();

	return 0;

}