The kth great number
The kth great number
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 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大的数字是谁中间呢会有一些新的数字加进来。我最初的想法,你加任你加,sort天下第一。然后就有了,加的时候,我不管,问的时候,我就排序一下,然后输出。超时,好吧,问题也不是很大,可能是我保存的数字太多了,于是这次就只保存k个,如果需要更新前面的k个数,我就sort 一下,不然我就不更新,然后超时。我就想,我可以考虑用插入排序去节省时间,那么我只要sort一次,应该不会有问题,可以我一想,插入排序后面移动时间比sort还要慢一些。感觉又不行。并且有一个很大的问题就在于,当sort排一个几乎是有序的序列的时候,时间会退化的很严重,时间复杂度会上升。所以,尝试了多次之后,选择放弃使用sort,于是用了优先队列。有小根堆去保存前k个,这样的话,取数方便的一下,时间复杂度也减下来了。
1 #include<bits/stdc++.h> 2 3 using namespace std; 4 5 priority_queue<int, vector<int>, greater<int> >a; 6 7 int main () { 8 char ch; 9 int n,k; 10 while (~scanf("%d%d",&n,&k)) { 11 while (!a.empty()) 12 a.pop(); 13 while (n--) { 14 int num; 15 getchar(); 16 scanf("%c", &ch); 17 if (ch == 'I') { 18 scanf("%d",&num); 19 if (a.size() < k) 20 a.push(num); 21 else{ 22 int mid = a.top(); 23 if (num > mid) { 24 a.pop(); //队列头部数据出队 25 a.push(num);//在队列尾部增加num数据 26 } 27 } 28 }else { 29 num = a.top(); 30 printf("%d\n",num); 31 } 32 } 33 } 34 return 0; 35 }