106. 动态中位数

题目链接

106. 动态中位数

动态维护中位数问题:依次读入一个整数序列, 每当已经读入的整数个数为奇数 时, 输出已读入的整数构成的序列的中位数。

解题思路

对顶堆

维护两个堆:大根堆:维护前 n/2 小数,小根堆:维护后 nn/2 大数,遇到奇数个数时,小根堆堆顶即为所求

  • 时间复杂度:O(nlogn)

代码

// Problem: 动态中位数 // Contest: AcWing // URL: https://www.acwing.com/problem/content/108/ // Memory Limit: 256 MB // Time Limit: 1000 ms // // Powered by CP Editor (https://cpeditor.org) // %%%Skyqwq #include <bits/stdc++.h> //#define int long long #define help {cin.tie(NULL); cout.tie(NULL);} #define pb push_back #define fi first #define se second #define mkp make_pair using namespace std; typedef long long LL; typedef pair<int, int> PII; typedef pair<LL, LL> PLL; template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; } template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; } template <typename T> void inline read(T &x) { int f = 1; x = 0; char s = getchar(); while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); } while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar(); x *= f; } priority_queue<int> q1; priority_queue<int,vector<int>,greater<int>> q2; int t,n; int main() { scanf("%d",&t); for(int i=1;i<=t;i++) { scanf("%*d%d",&n); printf("%d %d\n",i,(n+1)/2); while(q1.size())q1.pop(); while(q2.size())q2.pop(); int cnt=0; for(int j=1;j<=n;j++) { int x; scanf("%d",&x); if(q2.size()==0) q2.push(x); else if(q1.size()<q2.size()) { if(x>q2.top()) { int t=q2.top(); q2.pop(); q1.push(t); q2.push(x); } else q1.push(x); } else { if(x<q1.top()) { int t=q1.top(); q1.pop(); q2.push(t); q1.push(x); } else q2.push(x); } if(j&1) { printf("%d ",q2.top()); cnt++; if(cnt%10==0)puts(""); } } if(cnt%10!=0)puts(""); } return 0; }

__EOF__

本文作者acwing_zyy
本文链接https://www.cnblogs.com/zyyun/p/16095227.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   zyy2001  阅读(95)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示