Pagini recente » Cod sursa (job #1001046) | Cod sursa (job #503764) | Cod sursa (job #210846) | redsnow_3 | Cod sursa (job #1249931)
#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;
}