A16 对顶堆 第k大的数
视频链接:60 对顶堆 第k大的数_哔哩哔哩_bilibili
#include<cstring> #include<iostream> #include<algorithm> #include<queue> using namespace std; int main(){ int n,w; scanf("%d%d",&n,&w); //选手总数,获奖率 priority_queue<int> a; //大根堆 priority_queue<int,vector<int>,greater<int> > b; for(int i=1; i<=n; i++){ int x; scanf("%d",&x); if(b.empty()||x>=b.top()) b.push(x); //插入 else a.push(x); int k=max(1,i*w/100); //第k大 while(b.size()>k) a.push(b.top()), b.pop(); //调整 while(b.size()<k) b.push(a.top()), a.pop(); printf("%d ", b.top()); //取值 } }
练习:
Luogu RMID2 - Running Median Again
#include <cstdio> #include <iostream> #include <queue> using namespace std; int main(){ int t,x; scanf("%d",&t); //t组数据 while(t--){ priority_queue<int,vector<int>,less<int> > a; priority_queue<int,vector<int>,greater<int> > b; while(scanf("%d",&x)&&x){ if(x>0){ if(b.empty()||x>=b.top()) b.push(x); //插入 else a.push(x); int k=(b.size()+a.size())/2+1; //第k大数 while(b.size()>k) a.push(b.top()), b.pop(); //调整 while(b.size()<k) b.push(a.top()), a.pop(); } else printf("%d\n",b.top()), b.pop(); //取值,删除 } } return 0; }
#include<cstring> #include<iostream> #include<algorithm> #include<queue> using namespace std; int main(){ int n; scanf("%d",&n); priority_queue<int> a; //大根堆 priority_queue<int,vector<int>,greater<int> > b; for(int i=1; i<=n; i++){ int x; scanf("%d",&x); if(b.empty()||x>=b.top()) b.push(x); //插入 else a.push(x); int k=(i+1)/2; //第k大 while(b.size()>k) a.push(b.top()), b.pop(); //调整 while(b.size()<k) b.push(a.top()), a.pop(); if(i%2) printf("%d\n", b.top()); //取值 } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!