1. 程式人生 > >用優先順序佇列來實現樹的帶權路徑最小值的求解

用優先順序佇列來實現樹的帶權路徑最小值的求解

反覆選擇兩個最小的元素合併, 直到只剩下一個元素

程式碼:

#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