最大堆在面试题和笔试题中常常见到,练习一下吧,总没有坏处...
#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;
}