Pagini recente » Cod sursa (job #2797717) | Cod sursa (job #2276555) | Cod sursa (job #2620698) | Cod sursa (job #2947593) | Cod sursa (job #1546517)
#include<fstream>
using namespace std;
ifstream fin( "algsort.in" ); ofstream fout( "algsort.out" );
const int nmax = 500000;
int hn, h[ nmax + 1 ];
inline bool infata( int a, int b ) {
return ( h[ a ] < h[ b ] );
}
inline void heap_swap( int a, int b ) {
int aux = h[ a ]; h[ a ] = h[ b ]; h[ b ] = aux;
}
void urcare( int pos ) {
while ( pos > 1 && infata( pos, (pos >> 1) ) ) {
heap_swap( pos, (pos >> 1) );
pos >>= 1;
}
}
void coborare( int pos ) {
bool ok = 1;
while ( (pos << 1) <= hn && ok == 1 ) {
int q = pos << 1;
if ( q + 1 <= hn && infata( q + 1, q ) ) {
++ q;
}
if ( infata( q, pos ) ) {
heap_swap( pos, q );
pos = q;
} else {
ok = 0;
}
}
}
void heap_insert( int x ) {
h[ ++ hn ] = x;
urcare( hn );
}
void heap_erase() {
heap_swap( 1, hn );
-- hn;
coborare( 1 );
}
int main() {
int n, x;
fin >> n;
hn = 0;
for( int i = 1; i <= n; ++ i ) {
fin >> x;
heap_insert( x );
}
for( int i = 1; i <= n; ++ i ) {
fout << h[ 1 ] << " ";
heap_erase();
}
fout << "\n";
fin.close();
fout.close();
return 0;
}