算法简述
对于动态维护第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性质,主堆的元素必须全部是由副堆转移而来才行,否则,需要主副堆交换元素直到两堆顶端元素满足相应关系为止