霍夫曼的应用--leetcode 1167

https://leetcode.com/problems/minimum-cost-to-connect-sticks/

思路,将两个短的求和,然后放入数列中;再取两个短的;因此是霍夫曼树。

使用优先级队列即可:

class Solution {
public:
    int connectSticks(vector& sticks) {
        priority_queue,greater> q(sticks.begin(),sticks.end());
        int ans=0;
        while(q.size()>1){
            int a=q.top();
            q.pop();
            int b=q.top();
            q.pop();
            ans+=a+b;
            q.push(a+b);
        }
        return ans;
    }
};

 

你可能感兴趣的:(C++,leetcode)