用优先级队列来实现树的带权路径最小值的求解

反复选择两个最小的元素合并, 直到只剩下一个元素

代码:

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

priority_queue<int, vector<int>, greater<int>> q;

int main()
{
    int n, temp;
    cin >> n;
    for(int i = 0; i < n; i++)
    {
        scanf("%d", &temp);
        q.push(temp);
    }

    int ans = 0;
    while(q.size() > 1)
    {
        int x = q.top();
        q.pop();
        int y = q.top();
        q.pop();
        q.push(x + y);
        ans += x + y;
    }

    printf("%d", ans);

    return 0;
}

测试用例:

5

2 2 1 3 6

输出结果:

30

猜你喜欢

转载自blog.csdn.net/young_Tao/article/details/81631295