郭大侠与线上游戏

本文介绍了一种利用两个Set容器来维护数据流中位数的方法,该方法适用于在线更新数据集并快速获取当前中位数值的场景。通过案例演示了如何在插入、删除操作后调整数据分布以保持中位数的准确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://acm.uestc.edu.cn/#/problem/show/1339
本来想用线段树+数据离散化做,结果过不了,所以改用两个set容器,在要求的数分开保存。

#include<algorithm>
#include <iostream>
#include  <cstring>
#include   <cstdio>
#include    <queue>
#include      <set>
#define Max 100005
using namespace std;
queue<int>A;
set<int>big;
int op, key;
set<int> s;
void compare() {
    if (s.size() < big.size() - 1 ) {
        s.insert(*big.begin());
        big.erase(*big.begin());
    }
    else if (s.size() > big.size()) {
        big.insert(*s.rbegin());
        s.erase(*s.rbegin());
    }
}
int main() {
    int N;
    scanf("%d", &N);
    while (N--) {
        scanf("%d", &op);
        switch (op) {
        case 1:
            scanf("%d", &key);
            A.push(key);
            if (big.empty() || key > *big.begin()) {
                big.insert(key);
            }else{
                s.insert(key);
            }
            compare();
            break;
        case 2:
            key = A.front();
            A.pop();
            if (key > *s.rbegin()) {
                big.erase(big.find(key));
            }
            else{
                s.erase(s.find(key));
            }
            compare();
            break;
        case 3:
            printf("%d\n", *big.begin());
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值