首页 > 其他 > 详细

初涉“优先队列”

时间:2018-01-27 21:48:34      阅读:215      评论:0      收藏:0      [点我收藏+]

大概意思是将最小的两个pop出队列后相加push入队,类似哈夫曼树算法最后求和。

#include<bits/stdc++.h>
using namespace std;

struct cmp1{
    bool operator ()(int &a,int &b){
        return a>b;//最小值优先
    }
};

int main()
{
    priority_queue<int,vector<int>,cmp1>que1;//最小值优先

    int n;
    cin >> n;
    int a[n];
    for(int i=0;i < n;i++)
    {
        cin >> a[i];
        que1.push(a[i]);
    }

    int sum = 0;
    while(!que1.empty())
    {
        int x = que1.top();
        que1.pop();
        int y = que1.top();
        que1.pop();
        int hehe = x + y;
        sum += hehe;
        if(!que1.empty())
        {
            que1.push(hehe);
        }
        else break;
    }

    cout << sum << endl;

    return 0;
}

默认是最大值优先度最高,这里对操作符 “<” 进行了重载。

初涉“优先队列”

原文:https://www.cnblogs.com/cunyusup/p/8367223.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!