跳到正文

题解

P1168 multiset 题解

j136约 3 分钟
原文
文章信息与版本

文章信息

发布
2026年8月9日
收录
2026年8月28日
更新
2026年11月3日
篇幅
约 3 分钟
题目
P1168

版本

  1. v1当前

思路

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

  • 当 ∣S∣\left | S \right | 为奇数时,it\text{it} 指向 SS 的中位数(第 size+12\frac{size+1}{2} 小)。
  • 当 ∣S∣\left | S \right | 为偶数时,it\text{it} 指向 SS 的下中位数(第 size2\frac{size}{2} 小)。

移动规则

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

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

Code

C++
#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--;
    }
}
原文