一、题解方法
建立一个最小堆和一个最大堆,不断更新当前中位数,建立一个数组存入读入奇数个数时的中位数。
用stl中的优先队列存放最大堆、最小堆。
二、题解代码
1 #include "stdio.h" 2 #include "stdlib.h" 3 #include <iostream> 4 #include <queue> 5 #include <algorithm> 6 7 using namespace std; 8 9 const int MAX = 10000; 10 const int ACCOUNT = 10; 11 priority_queue<int, vector<int>, greater<int> > l; 12 priority_queue<int, vector<int>, less<int> > g; 13 14 int ans[MAX]; 15 int p; 16 17 int main() 18 { 19 int case_num; 20 scanf("%d", &case_num); 21 int i; 22 while(case_num--) 23 { 24 int case_order, num, mid; 25 scanf("%d%d%d", &case_order, &num, &mid); 26 int middle_num = (num+1) / 2; 27 printf("%d %d\n", case_order, middle_num); 28 p = 0; 29 ans[p++] = mid; 30 while ( !l.empty() ) l.pop(); 31 while ( !g.empty() ) g.pop(); 32 33 for(i = 2; i <= num; i++) 34 { 35 int temp; 36 scanf("%d", &temp); 37 if ( temp < mid ) 38 { 39 g.push(temp); 40 if ( g.size() - l.size() == 2 ) 41 { 42 l.push(mid); 43 mid = g.top(); 44 g.pop(); 45 } 46 } 47 else 48 { 49 l.push(temp); 50 if(l.size() - g.size() == 2) 51 { 52 g.push(mid); 53 mid = l.top(); 54 l.pop(); 55 } 56 } 57 if ( i & 1 ) 58 { 59 ans[p++] = mid; 60 } 61 } 62 for(i = 0; i < p; i++) 63 { 64 printf("%d", ans[i]); 65 if(i % ACCOUNT == 9 || i == p-1) 66 printf("\n"); 67 else 68 printf(" "); 69 } 70 71 72 } 73 return 0; 74 }