POJ 1442 优先队列

题意:有一些ADD和GET操作。n次ADD操作,每次往序列中加入一个数,由ADD操作可知序列长度为1-n时序列的组成。GET操作输入一个序列长度,输出当前长度序列第i大的元素的值。i初始为0,每次GET操作i先加1。给出的GET操作输入非降。
 
思路:求长度为k的序列的第i大元素。优先队列维护最大堆和最小堆分别存放前i-1大的元素和第i-第k大的元素。将当前序列的元素压入最小堆,如果最小堆的最小数大于最大堆的最大数则进行交换,保证最大堆中的所有数小于最小堆。因为i值每进行一次自增1,所以每次GET操作后将最小堆中的最小数弹出存入最大堆。
 
#include<cstdio>
#include<queue>
using namespace std;
priority_queue<int> bigque;
priority_queue<int, vector<int> ,greater<int> > smallque;
int num[30010];
int main() {
    int n,m,x;
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%d",&num[i]);
    int k=1;
    for(int i=1;i<=m;i++) {
        scanf("%d",&x);
        while(k<=x) {
            smallque.push(num[k]);
            if(!bigque.empty() && bigque.top()>smallque.top()) {
                int t=bigque.top();bigque.pop();smallque.push(t);
                t=smallque.top();smallque.pop();bigque.push(t);
            }
            k++;
        }
        printf("%d\n",smallque.top());
        int t=smallque.top();smallque.pop();bigque.push(t);
    }
    return 0;
}

 

posted @ 2016-08-05 12:56  _LinesYao  阅读(1135)  评论(0编辑  收藏  举报