The kth great number
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65768/65768 K (Java/Others)Total Submission(s): 8119 Accepted Submission(s): 3216
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 3HintXiao 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).
Source
题意:
输入n,k定义两种操作:“I” 代表插入,把I后面的数值插入一个已存在的数列,“Q”代表查询,查询该数列中第k大的数。
其中n代表总共有n次这样的操作,k表示第k大的数。
由于插入和查询操作是频繁且不规则的,需要一个高效的算法来提供支持。
由于每次访问的都是第k大的数,考虑使用优先队列。限定优先队列的长度为k,并从小到大排列,那么队首元素恒为第k大的数。
优先队列默认是从大到小排列的,如果要从小到大排列,要写成这样的形式:
priority_queue<int,vector<int>,greater<int> > q;
I操作:将元素推入队列,如果队列中元素数量大于k,将最小元素推出队列。
Q操作,直接取出队顶元素。
#include <iostream>
#include <cmath>
#include <queue>
#include <algorithm>
#include <cstring>
#include<cstdio>
using namespace std;
int main()
{
int n,k;
char ch;
int num;
while(cin>>n>>k)
{
priority_queue<int,vector<int>,greater<int> > q;
for(int i = 1;i<=n;i++)
{ getchar();
scanf("%c",&ch);
if(ch=='Q') cout<<q.top()<<endl;
else if(ch=='I')
{
scanf("%d",&num);
q.push(num);
if( q.size()>k ) q.pop();
}
}
}
return 0;
}