1. 程式人生 > >HDU4006 The kth great number————棧和佇列(優先佇列)

HDU4006 The kth great number————棧和佇列(優先佇列)

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=<k<=n<=1000000).

題意:
給你一些數字,問這些數字中,第k大的數字是誰
第一行n和k
n代表n個操作,I表示給你數字,Q 就是讓你輸出給你的這些數字中第k大的是幾
下邊n行,有n個操作

思路:
這道題用陣列模擬和用map都不能過,總是TLE
最後用優先佇列才過,優先佇列真是強

我們讓每次給的數字都存到優先佇列中,佇列的元素值越小,優先順序越高,我們只需要滿足佇列中有k個元素就行了

佇列中始終存留著最大的k個元素

#include<cstdio>
#include<cstring>
#include<string> #include<queue> #include<iostream> #include<map> #include<vector> #include<stack> #include<algorithm> using namespace std; typedef long long ll; int main() { ios::sync_with_stdio(false); int n,k; while(cin>>n>>k) { priority_queue<int,vector<int>, greater<int> > q; map<int ,int > m; char c; int z=0; for(int i=0;i<n;i++) { cin>>c; if(c=='I') { cin>>z; q.push(z); while(q.size()>k) q.pop(); } else//詢問第k大的數 cout<<q.top()<<endl; } } return 0; }