【题目描述】:
输入N个32位有符号整数,当已输入的个数为奇数个时,输出此时的中位数。
【输入描述】:
第一行一个整数N;
第二行N个32位有符号整数。
【输出描述】:
输出一行,N/2(上取整)个中位数,中间用空格隔开。
【样例输入】:
23
23 41 13 22 -3 24 -31 -11 -8 -7 3 5 103 211 -311 -45 -67 -73 -81 -99 -33 24 56
【样例输出】:
23 23 22 22 13 3 5 5 3 -3 -7 -3
【样例说明】:
【时间限制、数据范围及描述】:
时间:1s 空间:128M
对于 40%数据:N<=1000
对于所有数据:N<=100,000
代码
#include<algorithm>
#include<iostream> #include<cstring> #include<cstdio> #include<cmath> #include<queue> using namespace std; int n,m; priority_queue<int,vector<int>,greater<int> >q1; priority_queue<int,vector<int>,less<int> >q2; void add(int x){ if(q1.empty()){ q1.push(x); return ; } else if(x>q1.top()){ q1.push(x); } else{ q2.push(x); } while(q1.size()<q2.size()){ q1.push(q2.top()); q2.pop(); } while(q1.size()>q2.size()+1){ q2.push(q1.top()); q1.pop(); } } int main(){ scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&m); add(m); if(i%2){ printf("%d\n",q1.top()); } } return 0; }
对于本题,不可以每次都排一次序,否则会超时。
所以用一个大根堆和一个小根堆保存,每次只需先维护,然后就可以取出并输出了。