HDU 4006 The kth great number

这题的关键在于理解:要求第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();
			}
			else
				printf("%d\n",myQueue.top());
		}
	}

	return 0;
}


 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值