ural 1306 堆排序找中位数

题目要求找到一个数组的中位数

要是直接排序然后找到中位数的话,肯定是超内存的

选择堆排序,用STL中的make_heap, pop_heap, push_heap

代码如下:

#include <iostream>
#include <stdio.h>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;

int main() {
	int N, half, i;
	int temp, data[ 150001 ];

	while (scanf( "%d", &N ) != EOF) {
		half = N / 2 + 1;
		for ( i = 0; i < half; i++ )
			scanf( "%d", &data[ i ] );
		make_heap( data, data + half );

		while ( i++ < N ) {
			scanf( "%d", &temp );
			if ( temp < data[ 0 ] ) {
				pop_heap( data, data + half );
				data[ half - 1 ] = temp;
				push_heap( data, data + half );
			}
		}
		printf( "%.1f\n", N % 2 == 1 ? (float)data[ 0 ]: ( (float)data[ 0 ] + max( data[ 1 ], data[ 2 ] ) ) / 2 );
	}
	return 0;
}               
/*
7
3 6 7 2 1 5 4
4
3 6 4 5
*/


你可能感兴趣的:(ural 1306 堆排序找中位数)