优先队列(priority_queue)

int main()
{
	priority_queue<int> qi;
	for( int i = 0 ; i < 10 ; i ++ )
		qi.push(i);
	
	for( int i = 0 ; i < 10 ; i ++ ){
		int t = qi.top();
		cout << t << " ";
		qi.pop();
	}
	cout << endl;
	return 0;
}

默认最大堆  队首一定是最大的  但是队首的下一位不一定是次大的  因此在执行pop()的时候会执行shift_up  即弹出队首 经过调整把次大的当做队首 以此循环 最终会输出降序。

int tmp[100];
struct cmp1{
	bool operator()( int x , int y ){
		return x > y;	//小的优先级高
	}
};

struct cmp2{
	bool operator()( int x , int y ){
		return tmp[x] > tmp[y];
	}
};

struct node{
	int x , y;
	friend bool operator < ( node a , node b ){
		return a.x > b.x;	//	x小的优先级高
	}
};

priority_queue<int> q1;
priority_queue<int,vector<int>,cmp1 > q2;
priority_queue<int,vector<int>,cmp2 > q3;

priority_queue<node> q4;
int main()
{
	int n;
	node a;
	while( cin >> n ){
		for( int i = 0 ; i < n ; i ++ ){
			cin >> a.x >> a.y;
			q4.push(a);
		}
		while( !q4.empty()){
			cout << q4.top().x << " " << q4.top().y << endl;
			q4.pop();
		}
	}
	return 0;
}

其中pop()的定义:

    void pop()
        {    // erase highest-priority element
        pop_heap(c.begin(), c.end(), comp);
        c.pop_back();
        }

comp是重载<运算符的  在这里按照x的值构成最小堆 但是不理解运行机制是怎样的
 

 

/*********************************************************分割线****************************************************************************/

 

 



#include "pch.h"
#include <iostream>
#include <queue>
using namespace std;

int a[] = { 3,5,2,4,7,9,5,2,0,10 };
int main()
{
	int n = 10;
	priority_queue<int> q1;
	for (int i = 0; i < n; i++)
		q1.push(a[i]);
	for (; q1.size() > 0;) {
		cout << q1.top() << " ";
		q1.pop();
	}
	return 0;
}

默认最大堆   即最大的元素优先出队  

https://www.cnblogs.com/xzxl/p/7266404.html

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值