Pagini recente » Cod sursa (job #1496293) | Cod sursa (job #15384) | Cod sursa (job #2067951) | Cod sursa (job #586620) | Cod sursa (job #806950)
Cod sursa(job #806950)
#include<cstdio>
#include<algorithm>
using namespace std ;
#define NMAX 500005
int vheap[ NMAX ] , n ,ln_heap = 0 ;
void ins_heap ( int x )
{
++ln_heap ;
int ln = ln_heap ;
vheap[ ln_heap ] = x ;
while ( ln /2 >= 1 )
{
if( vheap [ ln/2 ] > vheap [ ln ] )
swap ( vheap [ ln/2 ] , vheap [ ln ] );
ln /= 2 ;
}
}
int elim_heap ( )
{
int ln = 1 ;
int y = vheap[ 1 ];
swap(vheap[ ln_heap ] , vheap [ ln ] );
int x ;
--ln_heap ;
bool ok = true ;
if(ln_heap >= 3)
while( ln *2 +1 <= ln_heap && ok == true )
{
ok = false ;
if( vheap[ ln*2 ] <= vheap [ ln*2 +1 ] )
x = ln*2 ;
else
x = ln*2 +1;
if( vheap [ ln ] > vheap [ x ] )
{
swap ( vheap [ x ] , vheap [ ln ] ) ;
ok = true ;
}
ln *= 2 ;
}
else
if ( ln_heap == 2 )
if(vheap[ 1 ] > vheap [ 2 ] ) swap( vheap[ 1 ] , vheap[ 2 ]);
return y;
}
int main()
{
freopen("algsort.in" , "r" , stdin);
freopen("algsort.out" , "w" , stdout);
scanf("%d",&n);
int x ;
for (int i = 1 ; i <=n ; ++i )
{
scanf("%d", &x) ;
ins_heap( x );
}
for (int i=1 ;i<=n; ++i)
printf("%d " ,elim_heap() );
return 0;
}