HDU 4006The kth great number(K大数 +小顶堆)

The kth great number

Time Limit:1000MS     Memory Limit:65768KB     64bit IO Format:%I64d & %I64u

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). 

题意:8个操作,每次操作两种形式,I表示插入一个数,Q表示输出当前的第 3 大数
最简单优先队列,从小到大顺序且容量为k,如果插入一个队列长度大于k时,那么队首出队,因为要求的是第 K 大的,那么之前的队首 肯定不是 第 K 大的,可能是 K + 1大...
也可以手写一个小定堆,之前知道用优先队列却不理解为什么要小顶堆,好弱啊,优先队列不就是小顶堆嘛=_=,原理一样。。。
 #include <cstring>
#include <algorithm>
#include <cstdio>
#include <iostream>
using namespace std;
const int Max = ;
int Heap[Max];
int cnt;
void up(int root) // 上调
{
while (root != ) // 调到根时就结束
{
int father = root / ;
if (Heap[father] > Heap[root])
{
swap(Heap[father], Heap[root]);
root = father;
}
else
break;
}
}
void heap_push(int num)
{
Heap[++cnt] = num;
up(cnt);
}
void down(int root)
{
while (root < cnt)
{
if (root * > cnt)
break;
int son = root * ;
if (root * + <= cnt) // 找到左右子节点中较小的那个
{
if (Heap[root * + ] < Heap[son])
son = root * + ;
}
if (Heap[root] > Heap[son])
{
swap(Heap[root], Heap[son]);
root = son;
}
else
break;
}
}
void heap_pop()
{
Heap[] = Heap[cnt--];
down();
}
int main()
{
int n, k;
while (scanf("%d%d", &n, &k) != EOF)
{
char str;
getchar();
cnt = ;
int num;
for (int i = ; i < n; i++)
{
scanf("%c", &str);
getchar();
if (str == 'I')
{
scanf("%d", &num);
getchar();
heap_push(num);
if (cnt > k)
heap_pop();
}
else
printf("%d\n", Heap[]);
}
}
return ;
}
上一篇:范仁义web前端介绍课程---4、html、css、js初体验


下一篇:c语言经典算法——查找一个整数数组中第二大数