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=
题目大意
如果输入的字符为‘I’表示读入一个数字,‘Q’表示将当前第K大的数输出。
思路
因为要输出的是第K大的数,所以可以采用优先队列并且控制优先队列的大小始终为K,如果大于K就pop(),这样队列的第一个元素即为第K大的数。
代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
int n,k;
int main()
{
while(~scanf("%d %d",&n,&k))
{
priority_queue< int , vector<int> , greater<int> > q;
char c;
int s;
for(int i=1;i<=n;i++)
{
cin>>c;
if(c=='I')
{
scanf("%d",&s);
q.push(s);
if(q.size()>k) q.pop();
}
else if(c=='Q')
{
printf("%d\n",q.top());
}
}
}
return 0;
}