A16 对顶堆 第k大的数

视频链接:60 对顶堆 第k大的数_哔哩哔哩_bilibili

Luogu P7072 [CSP-J2020] 直播获奖

 

 

复制代码
#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;
}
复制代码

Luogu P1168 中位数

复制代码
#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()); //取值
  }
}
复制代码

Luogu P1801 黑匣子

Luogu P2085 最小函数值

 

posted @   董晓  阅读(816)  评论(2编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示