【题解】洛谷P1801 黑匣子(堆)

怎么求一个堆内的第k小的值呢?我们可以把问题化为两个堆来解决。

存一个大根堆一个小根堆,小根堆负责读入元素。a数组记录要读的元素,b数组记录当前位置。读入当前的范围内饱含的元素,并把这个元素放到小根堆里,如果大根堆非空(注意!!!)并且大根堆堆顶比小根堆堆顶要大就交换堆顶,最后输出小根堆堆顶,把它堆顶扔到大根堆里,代表已经找到了第i小的数。关于大根堆里的数是否能更新小根堆上面已经操作过了。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<queue>
using namespace std;
int m,n;
int a[200010];
priority_queue<int,vector<int>,greater<int> > q;
priority_queue<int,vector<int>,less<int> > p;
int main()
{
	scanf("%d%d",&m,&n);
	for(int i=1;i<=m;i++)
	{
		scanf("%d",&a[i]);
	}
	int cnt=0;
	int w;
	for(int i=1;i<=n;i++)
	{
		
		scanf("%d",&w);
		while(cnt<w)
		{
			++cnt;
			q.push(a[cnt]);
			if(!p.empty()&&p.top()>a[cnt])
			{
				q.push(p.top());
				p.pop();
				p.push(a[cnt]);
				q.pop();
			}
		}
		
		printf("%d\n",q.top());
		p.push(q.top());
		q.pop();
		
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Rem_Inory/article/details/81489174