您的位置:首页 > 其它

【洛谷1801】黑匣子

2017-08-04 21:03 148 查看

题目链接:

https://www.luogu.org/problem/show?pid=1801

题解:

堆的巧妙应(ru)用(men)

由于所有询问第k小值的k是不断递增的,所以考虑可以使用堆来维护

建立一个大根堆和一个小根堆,用大根堆来维护前k小的数,大根堆中数的个数等于就应该等于k,此时堆顶就应该是第k小的数

加一个数时,把该数加入大根堆,如果大根堆的大小大于k,不断弹出堆顶加进小根堆

每次查询时直接访问大根堆的堆顶

如果要查询的第k小值的k增加,则将小根堆堆顶不断弹出,加入到大根堆中即可

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#define reg register int
using namespace std;
int n,m;

priority_queue<int> q1;
priority_queue<int,vector<int>,greater<int> > q2;
int a[200010],b[200010];

int main()
{
scanf("%d%d",&n,&m);
for(reg i=1;i<=n;i++) scanf("%d",&a[i]);
for(reg i=1;i<=m;i++) scanf("%d",&b[i]);
sort(b+1,b+m+1);
int pos=1;
for(int i=1;i<=n;i++)
{
q1.push(a[i]);
if(q1.size()>pos)
{
q2.push(q1.top());
q1.pop();
}
while(b[pos]==i)
{
pos++;
printf("%d\n",q1.top());
if(!q2.empty())
{
q1.push(q2.top());
q2.pop();
}

4000
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: