HDU 4006 The kth great number

来源:互联网 发布:lr推荐算法 编辑:程序博客网 时间:2024/05/22 16:45

这题的关键在于理解:要求第K大数,那么我们只保留前K个大数,并且按降序排列。这也就是说每加入一个数就找到这个数的位置。

然后将大于K个元素之外的数删除。

利用优先级队列就可以很好的做到这一点。

下面的代码中用到了两种优先级队列的写法。注释的和非注释的都可。并且时间都是62MS。

 

AC代码:

#include<iostream>#include<queue>using namespace std;/*struct node{int tmp;friend bool operator < (const node a,const node b){return a.tmp>b.tmp;}};*/int main(){int n,k,i,num;//node num;    char option;while(scanf("%d%d",&n,&k)!=EOF){//priority_queue<node> myQueue;priority_queue<int,vector<int>,greater<int> > myQueue;for(i=1;i<=n;i++){scanf(" %c",&option);if(option=='I'){scanf("%d",&num);myQueue.push(num);if(myQueue.size()>k)myQueue.pop();}elseprintf("%d\n",myQueue.top());}}return 0;}


 

 

 

原创粉丝点击