优先队列的用法(priority_queue)

13 篇文章 2 订阅
12 篇文章 4 订阅

(priority_queue)优先队列的应用

定义:priority_queue<Type, Container, Functional>
需要包含头文件
作用:可以自定义其中数据的优先级, 让优先级高的排在队列前面,优先出队。

和队列基本操作相同:

  • top 访问队头元素
  • empty 队列是否为空
  • size 返回队列内元素个数
  • push 插入元素到队尾 (并排序)
  • emplace 原地构造一个元素并插入队列
  • pop 弹出队头元素
  • swap 交换内容

当需要用自定义的数据类型时才需要传入这三个参数,使用基本数据类型时,只需要传入数据类型,默认是大顶堆。

`//升序队列,小顶堆
priority_queue <int,vector<int>,greater<int> > q;
//降序队列,大顶堆
priority_queue <int,vector<int>,less<int> >q;
//greater和less是std实现的两个仿函数(就是使一个类的使用看上去像一个函数。其实现就是类中实现一个operator(),这个类就有了类似函数的行为,就是一个仿函数类了)

自定义类型的例子

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

//方法1
struct tmp1 //运算符重载<
{
    int x;
    tmp1(int a) {x = a;}
    bool operator<(const tmp1& a) const
    {
        return x < a.x; //大顶堆
    }
};

//方法2
struct tmp2 //重写仿函数
{
    bool operator() (tmp1 a, tmp1 b)
    {
        return a.x < b.x; //大顶堆
    }
};

int main()
{
    tmp1 a(1);
    tmp1 b(2);
    tmp1 c(3);
    priority_queue<tmp1> d;
    d.push(b);
    d.push(c);
    d.push(a);
    while (!d.empty())
    {
        cout << d.top().x << '\n';
        d.pop();
    }
    cout << endl;

    priority_queue<tmp1, vector<tmp1>, tmp2> f;
    f.push(b);
    f.push(c);
    f.push(a);
    while (!f.empty())
    {
        cout << f.top().x << '\n';
        f.pop();
    }
}

题目

题目描述
自然界有一种物质,同种两个物质结合需要消耗的能量为两个物质的质量和。假设只能两两结合,根据输入的该类物质碎片质量,求全部碎片结合成一个整体,需要的最小能量。
Input Format
碎片总个数0<n<=50
n个碎片的质量【取值范围(0,10000)的n个整数】
Output Format
两两结合需要的最小能量
Example
Input
5
1 4 5 2 6
Output
39

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

int main()
{
	int n, t;
	int sum = 0;
	priority_queue<int, vector<int>, greater<int>> q;
	cin >> n;
	for(int i = 0; i < n; i++)
	{
		cin >> t;
		q.push(t);
	}
	for(int i = 0; i < n - 1; i++)
	{
		int a, b;
		a = q.top();
		q.pop();
		b = q.top();
		q.pop();
		sum += a + b;
		q.push(a + b);
	}
	cout << sum << endl;
	return 0;
}

参考来自:https://blog.csdn.net/weixin_36888577/article/details/79937886

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值