hdu4006 The kth great number(优先队列)

来源:互联网 发布:c语言趣味编程100例 编辑:程序博客网 时间:2024/05/12 02:34

hdu4006

题目

有插入和询问操作,插入的是数字,询问的是第k大的数是几。

思路

用优先队列维护一个有k个数的集合,未满k时入队,满k时判断是不是比最小的要大,大则进去,小的出来,这样查询的时候最小的就是第k大的了。相当于用较小的代价保住了我们需要的部分而且不出错。

代码

#include <iostream>#include <cstdio>#include <queue>#include <vector>using namespace std;int main(){    int n,k;    char s[20];    int temp;    int cnt;    while(scanf("%d %d",&n,&k)!=EOF)    {        priority_queue<int,vector<int>,greater<int> > q;        while(!q.empty()) q.pop();        cnt=0;        for(int i=0; i<n; i++)        {            scanf("%s",s);            if(s[0]=='I')            {                scanf("%d",&temp);                if(cnt<k)                {                    q.push(temp);                    cnt++;                }                else                {                    if(temp>q.top())                    {                        q.pop();                        q.push(temp);                    }                }            }            else if(s[0]=='Q')            {                printf("%d\n",q.top());            }        }    }    return 0;}
0 0