• 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
    ",smallque.top());
            int t=smallque.top();smallque.pop();bigque.push(t);
        }
        return 0;
    }
  • 相关阅读:
    156. Binary Tree Upside Down
    155. Min Stack
    154. Find Minimum in Rotated Sorted Array II
    153. Find Minimum in Rotated Sorted Array
    汉诺塔问题
    算法——二分搜索
    linux内核编程helloworld(中级)
    linux内核入门(1)——基本简介和编译
    linux网络编程概念(一)
    linux配置防火墙
  • 原文地址:https://www.cnblogs.com/LinesYao/p/5740886.html
Copyright © 2020-2023  润新知