您的位置:首页 > 编程语言 > C语言/C++

C++的priority_queue实现最大堆

2013-04-10 16:00 405 查看
最大堆在面试题和笔试题中常常见到,练习一下吧,总没有坏处...

#include<stdio.h>
#include<queue>

using namespace std;

const int k = 10;

struct node
{
int n;
int weight;
};
typedef struct node Node;

//以权重weight的值建立最大堆
struct cmp
{
bool operator()(const Node &a,const Node &b)
{
return a.weight < b.weight;
}
};

priority_queue<Node, vector<Node>, cmp> priorityQueue;

void initQueue()
{
for(int i=0; i<15; i++)
{
Node node;
scanf("%d %d", &node.n, &node.weight);
priorityQueue.push(node);
}
//Node n = priorityQueue.top();
//printf("%d %d\n", n.n, n.weight);
}
//取出k个元素
void getMembers(int k)
{
while(k--)
{
Node node = priorityQueue.top();
priorityQueue.pop();
printf("%d %d\n", node.n, node.weight);
}
}

int main()
{
initQueue();
getMembers(10);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: