P1168 multiset 题解

· · 题解

思路

考虑维护一个可重有序集合(std::multiset)S 的迭代器 \text{it},使得:

移动规则

设每次插入的数为 x,分类讨论。

插入前长度 插入后长度 x 与 \text{*it} 的关系 迭代器 \text{it} 移动规则 备注
偶数 奇数 x \ge \text{*it} it++ 新元素在 \text{it} 右侧,原 \text{it} 偏小,需要右移一位成为新的中位数。
偶数 奇数 x < \text{*it} 不动 新元素在 \text{it} 左侧,原 \text{it} 被挤到右侧,直接成为新的中位数。
奇数 偶数 x \ge \text{*it} 不动 新元素在 \text{it} 右侧,原 \text{it} 被挤到左侧,正好成为下中位数。
奇数 偶数 x < \text{*it} it-- 新元素在 \text{it} 左侧,原 \text{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--;
    }
}