栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Lintcode 1872 · Minimum Cost to Connect Sticks [Python]

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Lintcode 1872 · Minimum Cost to Connect Sticks [Python]

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

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/321915.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号