hdu40069(优先级队列)

来源:互联网 发布:sql in 两个字段 编辑:程序博客网 时间:2024/05/01 08:56

The kth great number

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


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大数,1=<k<=n<=1000000,由于n,k都比较大,不能用传统排序方法做,即便只存储k个数在处理也是不合理的,需要利用优先级队列来降低时间复杂度O(n*n)变成O(N^log),将队列中元素从小到大排序,若队列元素个数小于k,直接插入;若队列元素等于k,则需比较k与队头元素,若比队头元素小,不插入,反之则队头元素出队列,将新元素插入,保证队头元素总是第K大。
 
#include<iostream>#include<cstdio>#include<queue>#include<cstring>using namespace std;struct cmp{bool operator()(int a,int b){return a>b;}};int main(){char cmd[5];int i,n,k,a;while(~scanf("%d%d",&n,&k)){priority_queue<int,vector<int>,cmp>qq;for(i=0;i<n;i++){scanf("%s",cmd);if(cmd[0]=='I'){scanf("%d",&a);if(qq.size()<k)qq.push(a);else {int tmp=qq.top();if(a<tmp)continue;qq.pop();qq.push(a);}//cout<<qq.top()<<"  "<<endl;}else{printf("%d\n",qq.top());}}}return 0;}

原创粉丝点击