HDU 4006 The kth great number【优先队列】

来源:互联网 发布:java必读书籍推荐 编辑:程序博客网 时间:2024/05/09 21:24

优先队列和普通队列区别在于 普通队列总是队尾入元素,队首出元素,而优先队列赋予元素优先级,优先级最高的先出队列。


题目:http://acm.hdu.edu.cn/showproblem.php?pid=4006

题意:输入n和k,接下来n个操作,I代表入队,Q代表输出队列中第k大数

所以可以维护一个有前k大的数的队列,每次输出最小数(最小即第k大)即可,需要自己写比较操作规则

#include<queue>#include<cstdio>using namespace std; struct cmp{bool operator ()(int &a,int &b){return a>b;}};int main(){int n,k,num;char ch,xishou;freopen("in.txt","r",stdin);priority_queue<int,vector<int>,cmp>q;while(~scanf("%d%d",&n,&k)){while(n--){scanf("%c%c",&xishou,&ch);if(ch == 'I'){scanf("%d",&num);q.push(num);if(q.size()>k){q.pop();//超过k的不需要,直接去掉队首(最小的)}}elseprintf("%d\n",q.top());//队首是最小的数}while(!q.empty()){q.pop();}}return 0;}


0 0
原创粉丝点击