标签:
8 3 I 1 I 2 I 3 Q I 5 Q I 4 Q
1 2 3
Hint
Xiao Ming won‘t ask Xiao Bao the kth great number when the number of the written number is smaller than k. (1<=k<=n<=1000000).
题意大意, 就是给 一段数列, 求固定的第几大数, 细节请看 sampleinput
这题是优先队列的模板题。 当然是可以用 C ++ 的 stl。 但还是想了想, 自己搞下吧。
code:
#include <cstdio> #include <algorithm> #include <ctime> #include <cstdlib> using namespace std; typedef int elemType; const elemType all = 1000005; elemType M1[ all ]; // 运用函数指针 和 类型重定义, 可以封装成 函数模板。 void heap_push( elemType [], int, bool (*cmp)( elemType, elemType ) ); void heap_pop( elemType [], int, bool (*cmp)( elemType, elemType ) ); bool cmp_min( elemType elema, elemType elemb ); int main(void) { int m, n, tmp; char ch[5]; while( scanf( "%d%d", &n, &m ) != EOF ){ for( int i=0; i < m; ++ i ){ scanf( "%s%d", ch, M1+i ); heap_push( M1, i, cmp_min ); } for( int i=m; i < n; ++ i ){ scanf( "%s", ch ); if( ch[0] == ‘Q‘ ){ printf( "%d\n", M1[0] ); } else{ scanf( "%d", &tmp ); if( cmp_min( M1[0], tmp ) ){ heap_pop( M1, m-1, cmp_min ); M1[ m-1 ] = tmp; heap_push( M1, m-1, cmp_min ); } } } } return 0; } bool cmp_min( elemType elema, elemType elemb ) { return elema < elemb; } void heap_push( elemType container[], int num, bool (*cmp)( elemType elema, elemType elemb ) ) { while( num && cmp( container[ num ], container[ (num-1)/2 ] ) ){ swap( container[ num ], container[ (num-1)/2 ] ); num = (num-1)/2; } } void heap_pop( elemType container[], int num, bool (*cmp)( elemType elema, elemType elemb ) ) { swap( container[0], container[num] ); -- num; elemType spot = 0; bool isreturn = false; while( 2*spot+2 <= num && ( cmp( container[2*spot+1], container[spot] ) || cmp( container[ 2*spot+2 ], container[spot] ) ) ){ if( cmp( container[ 2*spot+1 ], container[ 2*spot+2 ] ) ){ swap( container[ 2*spot+1 ], container[ spot ] ); spot = 2*spot+1; } else{ swap( container[ 2*spot+2 ], container[ spot ] ); spot = 2*spot+2; } isreturn = true; } if( ! isreturn && 2*spot+1 <= num && cmp( container[ 2*spot+1 ], container[ spot ] ) ){ swap( container[ spot ], container[ 2*spot+1 ] ); } }
The kth great number_优先队列_priority
标签:
原文地址:http://www.cnblogs.com/seana/p/5325507.html