LintCode 1872: Minimum Cost to Connect Sticks (最小堆好题)

本文介绍了一种基于贪婪算法的解决方案,旨在找到将多个具有正整数长度的木棒连接成一根木棒所需的最小成本。通过使用最小堆数据结构,可以有效地找到并合并最短的两根木棒,直至只剩一根木棒。

1872. Minimum Cost to Connect Sticks

You have some sticks with positive integer lengths.

You can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y. You perform this action until there is one stick remaining.

Return the minimum cost of connecting all the given sticks into one stick in this way.

Example

Example 1:

Input:

 [2,4,3]

Output: 14

Explanation: First connect 2 and 3 to 5 and cost 5; then connect 5 and 4 to 9; total cost is 14

Example 2:

Input:

 [1,8,3,5]

Output: 30

Notice

1≤sticks.length≤10^​4

​​1≤sticks[i]≤10^​4

​​ 解法1:用minHeap
注意这题是基于贪婪法。但光排序sticks数组是不行的,因为connected之后的新stick也算一个stick。

class Solution {
public:
    /**
     * @param sticks: the length of sticks
     * @return: Minimum Cost to Connect Sticks
     */
    int MinimumCost(vector<int> &sticks) {
        int len = sticks.size();
        int sum = 0;
        priority_queue<int, vector<int>, greater<int>> minHeap(sticks.begin(), sticks.end());
        
        while(minHeap.size() > 1) {
            int cost = 0;
            cost += minHeap.top(); minHeap.pop();
            cost += minHeap.top(); minHeap.pop();
            minHeap.push(cost);
            sum += cost;
        }
        
        return sum;
    }
};

二刷: 不如上面的版本好。

class Solution {
public:
    /**
     * @param sticks: the length of sticks
     * @return: Minimum Cost to Connect Sticks
     */
    int minimumCost(vector<int> &sticks) {
        priority_queue<int, vector<int>, greater<int>> minHeap;
        for (auto stick : sticks) {
           minHeap.push(stick);
        }
        int res = 0;
        while (!minHeap.empty()) {
            int top1 = minHeap.top(), top2 = 0;
            minHeap.pop();
            if (!minHeap.empty()) {
                top2 = minHeap.top();
                minHeap.pop();
                int sum = top1 + top2;
                res += sum;
                if (minHeap.empty()) return res;
                minHeap.push(sum);
            } else {
                return res + top1;
            }
        }
        return res;
    }
};

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值