A16 对顶堆 第k大的数

A16 对顶堆 第k大的数_哔哩哔哩_bilibili

 

P7072 [CSP-J2020] 直播获奖 - 洛谷

// 对顶堆 O(nlogn)
#include<bits/stdc++.h>
using namespace std;

int n,w;
priority_queue<int> a; //大根堆
priority_queue<int,vector<int>,greater<int> > b;

int main(){
  scanf("%d%d",&n,&w); //选手总数,获奖率
  for(int i=1,x; i<=n; i++){
    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 T,x,len;
priority_queue<int,vector<int>,less<int> > a;
priority_queue<int,vector<int>,greater<int> > b;

int main(){
  scanf("%d",&T);
  while(T--){
    while(scanf("%d",&x)==1){
      if(x==0){
        while(!a.empty()) a.pop();
        while(!b.empty()) b.pop();
        len=0;
        break;
      }
      if(x==-1){
        if(len%2==0) printf("%d\n",a.top()),a.pop();
        else printf("%d\n",b.top()),b.pop();
        len--;
      }
      else{
        if(b.empty()||x>b.top()) b.push(x),len++;
        else a.push(x),len++;
      }
      while(a.size()>b.size()) b.push(a.top()),a.pop();
      while(b.size()>a.size()+1) a.push(b.top()),b.pop();
    }
  }
}

 

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 @ 2023-07-07 22:12  董晓  阅读(1255)  评论(3)    收藏  举报