经典题:不断求第k大数(巧用优先队列)(网赛)(4006)

来源:互联网 发布:听音识曲哪个软件更好 编辑:程序博客网 时间:2024/05/22 11:25

The kth great number

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


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 3I 1I 2I 3QI 5QI 4Q
 

Sample Output
123
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).

我们只需关注前k大的数,所以优先队列只保存最多k个数,队头就是所求,当新输入的比队头大时,需要更新队列(队头被压出,已经不需要这个数了)。


/*------------------Header Files------------------*/#include <iostream>#include <cstring>#include <string>#include <cstdio>#include <algorithm>#include <cstdlib>#include <ctype.h>#include <cmath>#include <stack>#include <queue>#include <map>#include <vector>#include <limits.h>using namespace std;/*------------------Definitions-------------------*/#define LL long long#define PI acos(-1.0)#define INF 0x3F3F3F3F#define MOD 10E9+7#define MAX 500050/*---------------------Work-----------------------*/priority_queue<int,vector<int>,greater<int> >q;void work(){int n,k;while(scanf("%d%d",&n,&k)==2){while(!q.empty()) q.pop();char s[10];int x;while(n--){scanf("%s",s);if(s[0]=='I'){scanf("%d",&x);if(q.size()<k) q.push(x);else if(q.top()<x){q.pop();q.push(x);}}else printf("%d\n",q.top());}}}/*------------------Main Function------------------*/int main(){//freopen("test.txt","r",stdin);//freopen("cowtour.out","w",stdout);//freopen("cowtour.in","r",stdin);work();return 0;}



0 0