saurus2
Saurus2
saurus2
전체 방문자
오늘
어제
  • 분류 전체보기
    • 개발
      • AJAX
    • ML Ops
    • Profile
    • 음식점
    • 배낭여행
    • 컴퓨터공학
      • 알고리즘 공부
      • C++
      • Sever 스터디
      • Java spring
      • 알고리즘 _ 문제해결
      • 딥러닝
      • Java 정리
      • Python
      • LeetCode 1000
      • Machine Learning Study
      • Sign language Detection Pro..
      • LeetCode Solutions
    • 비콘
    • 데일리 리포트
    • 유학일기
      • 영어 공부
      • Daily
    • AI Master Degree
      • Data Mining
      • AI and Data engineering
      • Math Foundations for Decisi..
      • Natural Language Processing

블로그 메뉴

  • 홈
  • 태그
  • 미디어로그
  • 위치로그
  • 방명록

공지사항

인기 글

태그

  • 알고리즘
  • 개발자
  • BFS
  • 취준
  • 파이썬
  • 릿코드
  • LeetCode
  • 개발자 취업준비
  • 알고리즘문제해결
  • two pointer
  • 리트코드
  • c++
  • 문제해결능력
  • 백준
  • 온라인저지
  • DFS
  • Python
  • 딥러닝
  • 딕셔너리
  • 취업준비

최근 댓글

최근 글

티스토리

hELLO · Designed By 정상우.
saurus2

Saurus2

컴퓨터공학/LeetCode 1000

[LeedCode] 1167. Minimum Cost to Connect Sticks 파이썬 Medium

2021. 11. 6. 09:35

문제 해석:

주어진 양의 정수 리스트에서 두개의 숫자를 뽑아 하나의 막대로 연결해야한다.
하나의 막대를 연결하는 비용은 각 막대의 값의 합과 같다.
모든 막대를 연결했을때 가장 최소비용은 얼마인가?

문제 해설:

1. 최소비용을 구하기 위해서는 가장 작은 막대들부터 연결해야한다.
2. 막대들 중에 작은 숫자를 순서대로 꺼내서 연산해야하기 때문에, Priority Queue, Heap을 사용할 수 있다.
(자료구조를 사용하지 않고, 매번 정렬하면 시간이 오래걸린다.)
3. 힙에서 두개의 숫자를 꺼내, 합하고 그비용을 결과에 더한다.
4. 그리고 연결되어 생성된 막대를 다시 힙에 넣는다.
5. 위의 과정을 막대가 1개가 될때까지 반복한다.

1167. Minimum Cost to Connect Sticks

You have some number of sticks with positive integer lengths. These lengths are given as an array sticks, where sticks[i] is the length of the ith stick.

You can connect any two sticks of lengths x and y into one stick by paying a cost of x + y. You must connect all the sticks until there is only 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 Explanation: You start with sticks = [2,4,3]. 1. Combine sticks 2 and 3 for a cost of 2 + 3 = 5. Now you have sticks = [5,4]. 2. Combine sticks 5 and 4 for a cost of 5 + 4 = 9. Now you have sticks = [9]. There is only one stick left, so you are done. The total cost is 5 + 9 = 14.

Example 2:

Input: sticks = [1,8,3,5] Output: 30 Explanation: You start with sticks = [1,8,3,5]. 1. Combine sticks 1 and 3 for a cost of 1 + 3 = 4. Now you have sticks = [4,8,5]. 2. Combine sticks 4 and 5 for a cost of 4 + 5 = 9. Now you have sticks = [9,8]. 3. Combine sticks 9 and 8 for a cost of 9 + 8 = 17. Now you have sticks = [17]. There is only one stick left, so you are done. The total cost is 4 + 9 + 17 = 30.

Example 3:

Input: sticks = [5] Output: 0 Explanation: There is only one stick, so you don't need to do anything. The total cost is 0.

 

Constraints:

  • 1 <= sticks.length <= 104
  • 1 <= sticks[i] <= 104

소스코드:

Heap

# 힙 풀이
class Solution:
    def connectSticks(self, sticks: List[int]) -> int:
        heapq.heapify(sticks)
        res = 0
        while len(sticks) > 1:
            v1 = heapq.heappop(sticks)
            v2 = heapq.heappop(sticks)
            res += (v1 + v2)
            heapq.heappush(sticks, v1 + v2)
        return res

Priority Queue

from queue import PriorityQueue
class Solution:
    def connectSticks(self, sticks: List[int]) -> int:
        pq = PriorityQueue()
        res = 0
        for i in sticks:
            pq.put(i)
        while pq.qsize() > 1:
            v1 = pq.get()
            v2 = pq.get()
            sv = v1 + v2
            res += sv
            pq.put(sv)
        return res

정렬

class Solution:
    def connectSticks(self, sticks: List[int]) -> int:
        stickSize = len(sticks)
        if stickSize <= 1:
            return 0
        sumV = 0
        li = sticks
        for i in range(stickSize - 1):
            li = sorted(li, reverse=True) # 4 3 2
            val1 = li.pop()
            val2 = li.pop()
            tmp = val1 + val2
            sumV += tmp
            li.append(tmp)
        return sumV

'컴퓨터공학 > LeetCode 1000' 카테고리의 다른 글

a+b=c 숫자식에서 각 숫자의 한자리 수 치환을 통해 식을 맞게 만드는 방법  (0) 2022.03.07
[LeedCode] 929. Unique Email Addresses 파이썬 (Easy)  (0) 2021.12.21
[LeedCode]819. Most Common Word 파이썬 Easy  (0) 2021.11.04
[LeedCode] 53. Maximum Subarray 파이썬 Easy  (0) 2021.11.04
[LeedCode] 175. Combine Two Tables SQL Easy  (0) 2021.11.03
    '컴퓨터공학/LeetCode 1000' 카테고리의 다른 글
    • a+b=c 숫자식에서 각 숫자의 한자리 수 치환을 통해 식을 맞게 만드는 방법
    • [LeedCode] 929. Unique Email Addresses 파이썬 (Easy)
    • [LeedCode]819. Most Common Word 파이썬 Easy
    • [LeedCode] 53. Maximum Subarray 파이썬 Easy
    saurus2
    saurus2
    Simple is Best

    티스토리툴바