HDU 2020 绝对值排序 堆优化
用二叉排序树写一个
#include<stdio.h> typedef struct Node { int data; struct Node *lc,*rc; }node,*Link; int n,f; inline int fab( int a ) { return a > 0 ? a : -a; } void insert( Link *L,int x ) { if( *L ) { if( fab( x ) > fab( ( *L ) -> data ) ) insert( &( *L ) -> lc,x ); else insert( &( *L ) -> rc,x ); } else { *L = new node; ( *L ) -> data = x; ( *L ) -> lc = ( *L ) -> rc = NULL; } } void print( Link L ) { if( L ) { print( L -> lc ); printf( f++ == 0 ? "%d" : " %d",L -> data ); print( L -> rc ); } } int main( ) { while( scanf( "%d",&n ),n ) { Link L; L = NULL; int x; f = 0; for( int i = 0; i < n; ++i ) scanf( "%d",&x ),insert( &L,x ); print( L ); puts( "" ); } return 0; }
用堆写一个
#include<stdio.h> int c,num[105],n; inline int fab( int a ) { return a > 0 ? a : -a; } void swap( int i,int j ) { int c; c = num[i]; num[i] = num[j]; num[j] = c; } void up( int x ) { if( x > 1 ) { int p = x / 2; if( fab( num[x] ) > fab( num[p] ) ) swap( x,p ),up( p ); } } void down( int x ) { int p = x * 2; if( p <= c )//这里是p <= c { if( p + 1 <= c ) p = fab( num[p] ) > fab( num[p+1] ) ? p : p + 1; if( fab( num[p] ) > fab( num[x] ) ) swap( x,p ),down( p ); } } int pop( ) { int x = num[1]; swap( 1,c-- ); down( 1 ); return x; } int main( ) { while( scanf( "%d",&n ),n ) { for( int i = 1; i <= n; ++i ) scanf( "%d",&num[i] ),up( i ); c = n; for( int i = 1; i <= n; ++i ) printf( i == 1 ? "%d": " %d",pop( ) ); puts( "" ); } return 0; }
本人还是新手 ,转载请注明来自Lvsi‘s home