初涉“优先队列”

大概意思是将最小的两个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