HDU 4006 The kth great number【优先队列】

题意:输入n行,k,如果一行以I开头,那么插入x,如果以Q开头,则输出第k大的数

用优先队列来做,将队列的大小维护在k这么大,然后每次取队首元素就可以了

另外这个维护队列只有k个元素的时候需要注意一下,先将输入的数都插入之后再将多余的数弹出去,这样才能保证留在队列里面的数是前k大的数

另外想到set里面的数是从小到大排列好了的,每次取第k个元素,但是超时了= =

 1 #include<iostream>  
 2 #include<cstdio>  
 3 #include<cstring> 
 4 #include <cmath> 
 5 #include<stack>
 6 #include<vector>
 7 #include<map> 
 8 #include<set>
 9 #include<queue> 
10 #include<algorithm>  
11 #define mod=1e9+7;
12 using namespace std;
13 
14 typedef long long LL;
15 const int INF = 0x7fffffff;
16 
17 
18 int main(){
19     
20     int n,m,i,j,k,ans;
21     char ch;
22     int x;
23     while(scanf("%d %d",&n,&k)!=EOF){
24         
25          priority_queue<int,vector<int>,greater<int> >pq;
26          
27         while(n--){
28             cin>>ch;
29             if(ch=='I'){
30                 cin>>x;
31                 pq.push(x);
32                 if(pq.size()>k) pq.pop();
33             }
34             
35             else if(ch=='Q'){
36                 int y=pq.top();
37                 printf("%d
",y);
38             }                        
39         }    
40     }
41     return 0;
42 }
View Code
原文地址:https://www.cnblogs.com/wuyuewoniu/p/4388095.html