如果用循环+sort的话肯定会爆,所以这里介绍一种简单的方法:
用两个堆,一个大根堆,一个小根堆。
------------------------------- ------------------------------------
1 3 5 7 8 | | 13 16 17 18
------------------------------- ------------------------------------
大根堆 小根堆
这样大根堆堆顶就是答案了。
中位数 传送门
代码如下:
#include<iostream>
#include<cstdio>
#include<queue>
using namespace std;
const int maxn=100005;
int n;
priority_queue<int> q1;
priority_queue<int,vector<int>,greater<int> > q2;
int main(){
cin>>n;
for(int i=1;i<=n;i++){
int a;
scanf("%d",&a);
int s1=q1.size();
int s2=q2.size();
if(s1==0) q1.push(a);
else{
int a1=q1.top();
if(a<=a1){
q1.push(a);
s1++;
}
else{
q2.push(a);
s2++;
}
}
while(s1-s2>1){
q2.push(q1.top());
q1.pop();
s1--;
s2++;
}
while(s2-s1>=1){
s2--;
s1++;
q1.push(q2.top());
q2.pop();
}
if(i%2==1) printf("%d\n",q1.top());
}
return 0;
}