思路
考虑维护一个可重有序集合(std::multiset) 的迭代器 ,使得:
- 当 为奇数时, 指向 的中位数(第 小)。
- 当 为偶数时, 指向 的下中位数(第 小)。
移动规则
设每次插入的数为 ,分类讨论。
| 插入前长度 | 插入后长度 | 与 的关系 | 迭代器 移动规则 | 备注 |
|---|---|---|---|---|
| 偶数 | 奇数 | it++ | 新元素在 右侧,原 偏小,需要右移一位成为新的中位数。 | |
| 偶数 | 奇数 | 不动 | 新元素在 左侧,原 被挤到右侧,直接成为新的中位数。 | |
| 奇数 | 偶数 | 不动 | 新元素在 右侧,原 被挤到左侧,正好成为下中位数。 | |
| 奇数 | 偶数 | it-- | 新元素在 左侧,原 偏大,需要左移一位成为下中位数。 |
Code
#include<bits/stdc++.h>
using namespace std;
multiset<int>s;
multiset<int>::iterator it;
int n,x;
int main(){
scanf("%d%d",&n,&x); // 第一个元素直接输出
s.insert(x),it=s.begin(),cout<<x<<'\n';
for(int i=2;i<=n;i++){
scanf("%d",&x),s.insert(x);
if(i&1){ // 插入后长度是奇数
if(x>=*it)it++;
cout<<*it<<'\n';
}else if(x<*it)it--;
}
}