ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

Lintcode 1872 · Minimum Cost to Connect Sticks [Python]

2021-10-13 09:02:48  阅读:227  来源: 互联网

标签:heapq Sticks Python res Lintcode cost connect heap sticks


题目在下方。读题目,有点儿费解,但是基本思路就是每次选择最小的棍子和第二小的棍子,加起来,丢回棍子堆里,然后继续重复,直到只剩下一个整的棍子。很容易想到用堆。

import heapq
class Solution:
    """
    @param sticks: the length of sticks
    @return: Minimum Cost to Connect Sticks
    """
    def MinimumCost(self, sticks):
        # write your code here
        heap = []
        for idx, stk in enumerate(sticks):
            heapq.heappush(heap, stk)
        res = 0
        while len(heap) != 1:
            x = heapq.heappop(heap)
            y = heapq.heappop(heap)
            res += x
            res += y
            newstk = x + y
            heapq.heappush(heap, newstk)
        #res += heap[0]
        return res

1872 · Minimum Cost to Connect Sticks
Algorithms
Medium
Accepted Rate
71%

DescriptionSolutionNotesDiscussLeaderboard
Description
In order to decorate your new house, you need to process some sticks with positive integer length.
You can connect any two sticks of lengths X and Y into one stick by paying a cost of X + Y. Due to the construction needs, you must connect all the bars into one.
Return the minimum cost of connecting all the given sticks into one stick in this way.
Please note that you can choose any order of sticks connection

1 \leq sticks.length \leq 10^41≤sticks.length≤10
4

1 \leq sticks[i] \leq 10^41≤sticks[i]≤10
4

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
Tags
Heap
Greedy

标签:heapq,Sticks,Python,res,Lintcode,cost,connect,heap,sticks
来源: https://blog.csdn.net/sinat_30403031/article/details/120736751

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有