The kth great number-优先队列的k维护

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


题意:题目会给出n个数,求第k大的数.

输入:第一行输入两个整数n 和 k

接下来有n行数据,输入的数据分为两种.

输入I 和 一个数字x   表示写入数字x

输入Q 表示进行一次询问 询问当前第k大的数是多少并输出这个数.


 
 
(1=<k<=n<=1000000).
数据范围可以用优先队列做,可是不是一直插入队列,然后 每次查询pop k个数 输出,再全部push进去。。k很大,肯定超时

可以这样: 重载队列为 小优先

先把前k个数push进队列,此后每一个数 进队列前要判断 如果大于队列的top,就先pop再push,否则 就不插入;

这样只维护一个k大小的队列,每次查询O(1)   每次插入logn;


#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <queue>
#include <map>
#include <set>
#include <vector>
using namespace std;
struct cmp
{
	bool operator()(const int &a,const int &b)
	{
		return a>b;
	}
}; 
int main()
{
    
	int n,i,tmp,k;
	while(cin>>n>>k)
	{
		priority_queue <int,vector<int>,cmp> qq;
		int cun=0;
		getchar();
		char op;
		for (i=1;i<=n;i++)
		{
			scanf("%c",&op);getchar();
			if (op=='I')
			{
				scanf("%d",&tmp);	getchar();
				if (cun>=k)
				{
					if (tmp>qq.top())
					{
						qq.pop();
						qq.push(tmp);
					}
				}
				else
				{
					qq.push(tmp); 
					cun++;
				}
			}
			else
			{
				printf("%d\n",qq.top());
			}
		}
	}
	
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值