P1168 multiset 题解
思路
考虑维护一个可重有序集合(std::multiset)
- 当
\left | S \right | 为奇数时,\text{it} 指向S 的中位数(第\frac{size+1}{2} 小)。 - 当
\left | S \right | 为偶数时,\text{it} 指向S 的下中位数(第\frac{size}{2} 小)。
移动规则
设每次插入的数为
| 插入前长度 | 插入后长度 | 迭代器 |
备注 | |
|---|---|---|---|---|
| 偶数 | 奇数 | 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--;
}
}