Pagini recente » Cod sursa (job #439711) | Cod sursa (job #788167) | Cod sursa (job #2397547) | Cod sursa (job #2330367) | Cod sursa (job #1456812)
#include <cstdio>
#include <algorithm>
#define NMAX 500007
using namespace std;
FILE *fin, *fout;
int n, h[NMAX], temp;
int father(int x)
{
return x/2;
}
int left(int x)
{
return x*2;
}
int right(int x)
{
return x*2+1;
}
int top()
{
return h[1];
}
void upheap(int x)
{
while(father(x)>0 && h[x] < h[father(x)])
{
swap(h[x], h[father(x)]);
x = father(x);
}
}
void downheap(int x)
{
int best = x;
if(left(x) <= h[0]) if(h[left(x)] < h[best]) best = left(x);
if(right(x) <= h[0]) if(h[right(x)] < h[best]) best = right(x);
while(best != x)
{
swap(h[x], h[best]);
x = best;
if(left(x) <= h[0]) if(h[left(x)] < h[best]) best = left(x);
if(right(x) <= h[0]) if(h[right(x)] < h[best]) best = right(x);
}
}
void hinsert(int val)
{
h[0]++;
h[h[0]] = val;
upheap(h[0]);
}
void herase(int x)
{
swap(h[h[0]], h[x]);
h[0]--;
downheap(x);
}
int main()
{
fin = freopen("algsort.in", "r", stdin);
fout = freopen("algsort.out", "w", stdout);
scanf("%d", &n);
for(int i = 1; i<= n; i++)
{
scanf("%d", &temp);
hinsert(temp);
}
for(int i = 1; i<= n; i++)
{
printf("%d ", top());
herase(1);
}
printf("\n");
fclose(fin);
fclose(fout);
return 0;
}