1167 Minimum Cost to Connect Sticks

本文探讨了一种算法问题,即如何以最小的成本将一组具有不同长度的棍子通过连续合并成一根棍子。通过分析发现,应优先合并较短的棍子以减少总成本,并提供了解决方案的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 题目

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 1:

Input: sticks = [2,4,3]
Output: 14

Example 2:

Input: sticks = [1,8,3,5]
Output: 30

2 尝试解

2.1 分析

给定一组正数sticks,每次操作可以将其中两个正数X和Y合并,操作的代价为X+Y。问要合并所有正数使得最后仅有一个正数剩余,所需的最小操作代价。

每次操作减少一个数,所以共需要sticks.size()-1次操作。考虑sticks = [1,8,3,5],越早合并的数,被重复计算的次数越多。所以我们希望长度短的早合并,长度长的晚合并。即每次取数组中最小的两个数合并。

2.2 代码

class Solution {
public:
    int connectSticks(vector<int>& sticks) {
        priority_queue<int,vector<int>,greater<int>> saver;
        int result = 0;
        for(auto stick : sticks)
            saver.push(stick);
        while(saver.size() > 1){
            int first = saver.top();
            saver.pop();
            int second = saver.top();
            saver.pop();
            result += first + second;
            saver.push(first+second);
        }
        return result;
    }
};

3 标准解

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值