您的位置:首页 > 其它

Hdu 4006 The kth great number (第k大元素 优先队列的几种写法)

2014-02-13 19:57 357 查看
题意:不断地读入数据,询问第k大的是多少。

思路:维护只有k个元素且队首元素最小的优先队列

总结下常用的三种写法,个人还是喜欢结构体这种。

#include<cstdio>
#include<queue>
using namespace std;

struct Node
{
	int data;
	bool operator < (const Node b) const
	{
		return data>b.data;
	}
}node;
//重载 “()” 操作符
struct myComp
{
    bool operator () (const int a,const int b)
    {
        return a>b;
    }
};

int main ()
{
	int n,k,num;
    char str[4];
	while (~scanf("%d%d",&n,&k))
	{
		priority_queue<Node> Q;
		//priority_queue<int,vector<int>,greater<int> > Q;
		//priority_queue<int,vector<int>,myComp > Q;

		for (int i=1;i<=n;i++)
		{
			scanf("%s",str);
			if (str[0]=='I')
			{
			    //scanf("%d",&num);
			    scanf("%d",&node.data);
				Q.push(node);
				if (Q.size()>k)
					Q.pop();
			}
			else
				printf("%d\n",Q.top());
		}
	}
	return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: