Pagini recente » Istoria paginii utilizator/vladdstoica | Monitorul de evaluare | Cod sursa (job #916079) | Cod sursa (job #2173346) | Cod sursa (job #1465963)
#include <fstream>
#include <algorithm>
#define NMAX 1000005
#define MAX (1 << 31) - 1
using namespace std;
ifstream f("algsort.in");
ofstream g("algsort.out");
int heap[NMAX], n = 0, nr, x, i;
int father(int x)
{
return x/2;
}
int left_son(int x)
{
return 2*x;
}
int right_son(int x)
{
return 2*x + 1;
}
void get_down(int k)
{
int aux;
do
{
aux = 0;
if (left_son(k) <= n)
aux = left_son(k);
if (right_son(k) <= n && heap[aux] > heap[right_son(k)])
aux = right_son(k);
if (heap[right_son(k)] > heap[k] && heap[left_son(k)] > heap[k])
aux = 0;
if (aux != 0)
{
swap(heap[k], heap[aux]);
k = aux;
}
}while (aux);
}
void get_up(int k)
{
while (k > 1 && heap[k] < heap[father(k)])
{
swap(heap[k], heap[father(k)]);
k = father(k);
}
}
void insert_heap(int x)
{
heap[++n] = x;
get_up(n);
}
void delete_heap(int k)
{
heap[k] = heap[n];
heap[n] = MAX;
n --;
get_down(k);
}
int main()
{
f >> nr;
for (i=1; i<=nr; ++i)
{
f >> x;
insert_heap(x);
}
while (n)
{
g << heap[1] << " ";
delete_heap(1);
}
return 0;
}