Pagini recente » Cod sursa (job #1087626) | Cod sursa (job #2721086) | Cod sursa (job #1825180) | Cod sursa (job #179304) | Cod sursa (job #2287626)
#include <iostream>
#include <fstream>
using namespace std;
class Heap {
private:
int Size;
int v[500100];
int getParent(int pos) { return pos / 2;}
int getValue(int pos) {return v[pos];}
int hasParent(int pos) { return (pos != 1); }
int hasLeftChild(int pos) { return 2 * pos <= Size; }
int hasRightChild(int pos) { return 2 * pos + 1 <= Size;}
int getLeftChildValue(int pos) {return v[2 * pos];}
int getRightChildValue(int pos) {return v[2 * pos + 1];}
int getLeftChildPos(int pos) {return 2 * pos;}
int getRightChildPos(int pos) {return 2 * pos + 1;}
void HeapifyUp(int x, int pos) {
bool canContinue = true;
while (hasParent(pos) == 1 && canContinue) {
canContinue = false;
int parentPos = getParent(pos);
int parentValue = getValue(getParent(pos));
if (parentValue > x) {
int aux = v[parentPos];
v[parentPos] = x;
v[pos] = aux;
canContinue = true;
pos = getParent(pos);
x = v[parentPos];
}
}
}
void HeapifyDown(int x, int pos) {
bool canContinue = true;
while (canContinue == true) {
canContinue = false;
if (hasLeftChild(pos) ) {
if (hasRightChild(pos)) {
int LeftChildValue = getLeftChildValue(pos);
int RightChildValue = getRightChildValue(pos);
int LeftChildPos = getLeftChildPos(pos);
int RightChildPos = getRightChildPos(pos);
if (LeftChildValue < RightChildValue) {
if (LeftChildValue < x) {
int aux = v[LeftChildPos];
v[LeftChildPos] = v[pos];
v[pos] = aux;
pos = getLeftChildPos(pos);
x = v[LeftChildPos];
canContinue = true;
}
} else {
if (RightChildValue < x) {
int aux = v[RightChildPos];
v[RightChildPos] = v[pos];
v[pos] = aux;
pos = getRightChildPos(pos);
x = v[RightChildPos];
canContinue = true;
}
}
} else {
int LeftChildValue = getLeftChildValue(pos);
int LeftChildPos = getLeftChildPos(pos);
if (LeftChildValue < x) {
int aux = v[LeftChildPos];
v[LeftChildPos] = v[pos];
v[pos] = aux;
pos = getLeftChildPos(pos);
x = v[LeftChildPos];
canContinue = true;
}
}
}
}
}
public:
Heap() {
Size = 0;
}
void push(int x) {
Size ++;
v[Size] = x;
HeapifyUp(x, Size);
}
void pop() {
swap(v[Size], v[0]);
Size --;
HeapifyDown(v[0], 0);
}
int getRoot() { return v[1];}
};
int main() {
ifstream f("algsort.in");
ofstream g("algsort.out");
int n;
f >> n;
Heap h;
int x;
for (int i = 0; i < n; ++i) {
f >> x;
h.push(x);
}
for (int i = 0; i < n; ++i) {
g << h.getRoot() << " ";
h.pop();
}
return 0;
}