对顶堆(动态维护第k大/小)

算法简述

对于动态维护第k小的问题,可以用一个size为k的大根堆,来维护,大根堆的顶部元素即第k小元素,维护大根堆需要一个小根堆,由小根堆向大根堆传递元素,即对顶堆。
若当前大根堆size为k,第k+1小元素即小根堆的顶部元素

例题

点名

题目描述

在这里插入图片描述
保证B为增序

AC代码
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
#include<climits>
#include<cctype>
#include<vector>
#include<map>
#include<queue>
#include<set>
#include<stack>
#include<list>
#include<string>
#include<string.h>
using namespace std;
#pragma warning(disable:4996)
#define mx(a,b) (a>b?a:b)
#define mn(a,b) (a<b?a:b)
#define sfd(x) scanf("%d",&x)
#define sflld(x) scanf("%lld",&x)
#define ini(x,y) memset(x,y,sizeof(x))
typedef long long ll;
const int maxn = 30005;
priority_queue<ll,vector<ll> > q1;
priority_queue<ll, vector<ll>, greater<ll> > q2;
ll a[maxn];
int b[maxn];
int main()
{
	int n, m;
	sfd(n), sfd(m);
	for (int i = 1; i <= n; i++)
	{
		sflld(a[i]);
	}
	b[0] = 0;
	for (int i = 1; i <= m; i++)
	{
		sfd(b[i]);
	}
	for (int i = 1; i <= m; i++)
	{
		for (int j = b[i - 1] + 1; j <= b[i]; j++)
		{
			q1.push(a[j]);
			q2.push(q1.top());
			q1.pop();
		}
		q1.push(q2.top());
		q2.pop();
		cout << q1.top() << '\n';
	}
}
历史错误代码
for (int i = 1; i <= m; i++)
	{
		for (int j = b[i - 1] + 1; j <= b[i]; j++)
		{
			q1.push(a[j]);
		}
		while (q1.size() > i)
		{
			q2.push(q1.top());
			q1.pop();
		}
		while (q1.size() < i)
		{
			q1.push(q2.top());
			q2.pop();
		}
		cout << q1.top() << '\n';
	}

能够实现第k性质,主堆的元素必须全部是由副堆转移而来才行,否则,需要主副堆交换元素直到两堆顶端元素满足相应关系为止

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值