题意:传送门
题解:动态维护中位数问题,两种解法,解法一是使用对顶堆,建立两个二叉堆,一个小根堆,一个大根堆,依次读入的过程中,设当前长度为
M
M
M,始终保持:
- 序列中从小到大排名为
1
∼
M
2
1 \sim \frac{M}{2}
1∼2M的整数存储在大根堆
priority_queue<int> max_heap
中。 - 序列中从小到大排名为
M
2
∼
M
\frac{M}{2}\sim M
2M∼M的整数存储在小根堆
priority_queue<int, vector<int>, greater<int>> min_heap
中
任何时候,如果某一个堆中的元素过多,打破了这个性质,就取出该堆的堆顶插入到另外一个堆,这样一来,小根堆中的中位数就是序列的中位数。
每次新读入一个数
X
X
X,若
X
X
X比中位数小,插入到大根堆中,否则插入到小根堆,在插入后再检查并维护上面的两个性质即可。
附上代码(略丑略复杂):
#include<iostream>
#include<cstdio>
#include<queue>
#define mod 998244353
#define pi acos(-1)
#define inf 0x7fffffff
#define eps 1e-6
#define pa pair<int,int>
#define ll long long
using namespace std;
inline int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int T,n,id,a,ans,cnt;
int main()
{
T=read();
while(T--){
priority_queue <int,vector<int>,greater<int> > s;
priority_queue <int,vector<int>,less<int> > b;
id=read();n=read();cnt=0;
printf("%d %d\n",id,(n+1)/2);
for(int i=1;i<=n;i++){
a=read();
if(i==1){
s.push(a);
ans=a;
}else if(i%2){
if(a>ans){
s.push(a);
}else{
b.push(a);
int tmp=b.top();
b.pop();
s.push(tmp);
ans=s.top();
}
}else{
if(a>ans){
s.push(a);
int tmp=s.top();
s.pop();
b.push(tmp);
ans=s.top();
}else{
b.push(a);
}
}
if(i%2){
cnt++;
printf("%d ",ans);
if(cnt==10||i==n){
cnt=0;
printf("\n");
}
}
}
}
return 0;
}