http://acm.hdu.edu.cn/showproblem.php?pid=4006
题意:题目会给出n个数,求第k大的数.
输入:第一行输入两个整数n 和 k
接下来有n行数据,输入的数据分为两种.
输入I 和 一个数字x 表示写入数字x
输入Q 表示进行一次询问 询问当前第k大的数是多少并输出这个数.
数据范围可以用优先队列做,可是不是一直插入队列,然后 每次查询pop k个数 输出,再全部push进去。。k很大,肯定超时(1=<k<=n<=1000000).
可以这样: 重载队列为 小优先
先把前k个数push进队列,此后每一个数 进队列前要判断 如果大于队列的top,就先pop再push,否则 就不插入;
这样只维护一个k大小的队列,每次查询O(1) 每次插入logn;
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <algorithm>
#include <iostream>
#include <queue>
#include <map>
#include <set>
#include <vector>
using namespace std;
struct cmp
{
bool operator()(const int &a,const int &b)
{
return a>b;
}
};
int main()
{
int n,i,tmp,k;
while(cin>>n>>k)
{
priority_queue <int,vector<int>,cmp> qq;
int cun=0;
getchar();
char op;
for (i=1;i<=n;i++)
{
scanf("%c",&op);getchar();
if (op=='I')
{
scanf("%d",&tmp); getchar();
if (cun>=k)
{
if (tmp>qq.top())
{
qq.pop();
qq.push(tmp);
}
}
else
{
qq.push(tmp);
cun++;
}
}
else
{
printf("%d\n",qq.top());
}
}
}
return 0;
}
本文介绍了一种使用优先队列(小顶堆)高效求解数组中第K大元素的方法,通过维护一个固定大小为K的优先队列实现快速查询与更新,适用于在线查询场景。

1372

被折叠的 条评论
为什么被折叠?



