标准库函数求解 哈法曼树带权路径长度和

#include <iostream>
#include <algorithm>
#include<string>
#include<queue>
#include<functional>

using namespace std;

//使用优先队列实现最小堆
priority_queue<int, vector<int>, greater<int>>q;

void main()
{
 
    int n;
    int a, b, res;
    while (cin >> n)
    {
        int a;
        res = 0;

        while (!q.empty())q.pop();
        while (n--)
        {
            cin >> a;
            q.push(a);
        }
        while (q.size() > 1){
            a = q.top();
            q.pop();
            b = q.top();
            q.pop();
            res += a + b;
            q.push(a + b);
        }
        cout << res<< endl;
    }


}

猜你喜欢

转载自blog.csdn.net/KingsCC/article/details/81675783