HDOJ 4006 The kth great number(优先队列)

题目:

The kth great number

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65768/65768 K (Java/Others)
Total Submission(s): 3770    Accepted Submission(s): 1581


Problem Description
Xiao Ming and Xiao Bao are playing a simple Numbers game. In a round Xiao Ming can choose to write down a number, or ask Xiao Bao what the kth great number is. Because the number written by Xiao Ming is too much, Xiao Bao is feeling giddy. Now, try to help Xiao Bao.


 

Input
There are several test cases. For each test case, the first line of input contains two positive integer n, k. Then n lines follow. If Xiao Ming choose to write down a number, there will be an " I" followed by a number that Xiao Ming will write down. If Xiao Ming choose to ask Xiao Bao, there will be a "Q", then you need to output the kth great number.


 

Output
The output consists of one integer representing the largest number of islands that all lie on one line.


 

Sample Input
  
  
8 3 I 1 I 2 I 3 Q I 5 Q I 4 Q


 

Sample Output
  
  
1 2 3
Hint
Xiao Ming won't ask Xiao Bao the kth great number when the number of the written number is smaller than k. (1=<k<=n<=1000000).

 

题目链接:

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

 

题意:

I表示输入数据,当输入Q的时候就在输入的那些数据中找第K大的数

 

思路:

刚开始用sort排序,因为数据量大,会超时,所以必须用最小优先队列(降序排序),先把k个数压进队列,之后的数和队头比较,如果比队头校就不进队,若比队头大,就队头出队,然后压进队列里。。。

 

代码:

/*
sort不行 // 数据大  会超市
队列  最小优先队列

#include<iostream>
#include <algorithm>
using namespace std;
int used[10000+10];
bool cmp(const int a,const int b)
{
	return a > b;
}
int main()
{
	int n,k;
	char ch;
	int i=0;
	int a[10000+10];
	int flag = 0;
	
	while(cin>>n>>k;)
	{
		memset(used, 0 ,sizeof(used));
		cin>>ch;
		if(ch == 'I')
		{
			cin>>a[i++];
		}
		else if(ch == 'Q')
		{
			sort(a,a+n,cmp);
			cout<<a[k-1-flag]<<endl;
			flag++;
		}
	}
	
}
*/



#include<iostream>
#include<queue>
using namespace std;


const int maxn = 1000000 + 10;


struct node
{
	int t;
	const bool operator < (const struct node &a) const 
	{
		return t > a.t;
	}
}a[maxn];


priority_queue<struct node > q;

int main()
{
	int temp;
	int n,k;
	char ch;
	int i=0;
	int flag = 0;
	while(cin>>n>>k)
	{
		while(k--)
		{	
			n--;
			cin>>ch;
			if(ch == 'I')
			{
				cin>>a[++i].t;  //不能用a[i++];
				q.push(a[i]);
			//	i++;
			}
		}

		while(n--)
		{
			cin>>ch;
			if(ch == 'I')
			{
				cin>>a[++i].t;
				temp = q.top().t;
				if(a[i].t > temp)
				{
					q.pop();
					q.push(a[i]);
				}
			//	i++;
			}
			else if(ch == 'Q')
			{
				cout<<q.top().t<<endl;
			}
			
		}

		while(!q.empty())
		{
			q.pop();
		}
	}
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值