对顶堆模板

Template

一.求中位数;

priority_queue<int> h// 大根堆;
priority_queue<int,vector<int>,greater<int>> g//小根堆;

void insert(int x)//对顶堆求中位数模板
{
    
    
	if(!h.size()||x <= h.top()) h.push(x);
	else	g.push(x);
	//对弹
	if(g.size()>h.size()+1)	h.push(g.top()),g.pop();
	if(h.size()>g.size()+1)	g.push(h.top()),g.pop();
	return ;
}

二.求第K小/大;

使用大根堆来维护前 k − 1 k-1 k1小,用小根堆去存剩下的数;
例题:洛谷P1801 黑匣子
code:

/*入门就算成功!*/
#include<bits/stdc++.h>
using namespace std;
#define gcd __gcd
#define _orz ios::sync_with_stdio(false)
#define fi first
#define se second
#define lc i<<1
#define rc i<<1|1
#define sf scanf
#define pf printf
#define mem(str,num) memset(str,num,sizeof(str))
#define lowbit(a) ((a)&(-a))
typedef long long ll;
typedef pair<int,int> pll;
typedef pair<ll,ll> pLL;
const double esp = 1e-6;
const int inf = 0x3f3f3f3f;
const long long mod = 1e9+7;
const int N = 2e5+10;
ll qpow(ll a, ll b){
    
    ll res = 1; while(b){
    
    if(b&1)res = a*res%mod;b >>= 1;a=a*a%mod;}return res;}
int n,m;
priority_queue<int>h;
priority_queue<int,vector<int>,greater<int>>g;
ll a[N],b[N];
int main()
{
    
    
    cin>>m>>n;
    for(int i = 1; i <= m; i++) cin >> a[i];
    for(int i = 1; i <= n; i++) cin >> b[i];

    int cnt = 1;
    int idx = 1;
    for(int i = 1;i <= n;i++){
    
    
        int j = b[i];
        for(int k = idx;k <= j;k++){
    
    
            h.push(a[k]);
            if(h.size()>=cnt){
    
    
                g.push(h.top());
                h.pop();
            }
        }
        cnt++;
        cout << g.top() << endl;
        idx = j + 1;
        h.push(g.top());
        g.pop();
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_51687628/article/details/119006562
今日推荐