您的位置:首页 > 其它

POJ 1442 Black Box

2017-01-14 12:04 375 查看
**题目大意**
有一个黑盒子(Black Box)很神奇,可以获取其中第i小的元素。题目中有两种操作分别为ADD 和 GET,ADD操作序列为A,GET操作序列为u,GET初始值 i 为0,每次进行GET操作后 i 值加1。输出每次的第i小的值为多少。
**解题思路**
优先队列的简单应用,维护两个堆,一个大顶堆,一个小顶堆,将前u(p)个数据先加入小顶堆中,每次读取一个u(p)元素就将小顶堆的堆顶元素加入大顶堆中,当向小顶堆加入元素时要加入判断,判断小顶堆堆顶是否大于大顶堆堆顶,若否,则将两个堆顶元素互换。
**代码**
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
#include <vector>
#include <iostream>
using namespace std;
int num[50010];
int com[50010];
int main()
{
int m,n,last,now,key1,key2;
priority_queue<int,vector<int>,greater<int> > smallheap;
priority_queue<int,vector<int>,le
9f8e
ss<int> > bigheap;
scanf("%d%d",&m,&n);
for(int i=1;i<=m;i++)
scanf("%d",&num[i]);
com[0]=0;
for(int i=1;i<=n;i++){
scanf("%d",&com[i]);
for(int j=1;j<=(com[i]-com[i-1]);j++){
smallheap.push(num[com[i-1]+j]);
if(!bigheap.empty()&&!smallheap.empty()&&smallheap.top()<bigheap.top()){
key1=smallheap.top();key2=bigheap.top();
smallheap.pop();bigheap.pop();
smallheap.push(key2);bigheap.push(key1);
}
}
printf("%d\n",smallheap.top());
key1=smallheap.top();
smallheap.pop();
bigheap.push(key1);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: