알고리즘 - 게임 아이템 python

pyhoo·2020년 9월 11일
0

Algorithm

목록 보기
1/11
post-thumbnail

import heapq
from _collections import deque as queue

def solution(healths, items):
    healths.sort()
    new_items = queue(sorted([(h, a, idx) for idx, (a, h) in enumerate(items)]))
    heap = []
    answer = []
    print(healths)
    print(new_items)
    for health in healths:
        while new_items:
            h, a, idx = new_items[0]
            if health - h < 100:
                break
            h, a, idx = new_items.popleft()
            heapq.heappush(heap, (-a, idx + 1))
        if heap:
            answer.append(heapq.heappop(heap)[1])
    return sorted(answer)
  • 피드백
    나는 if문이 for문 밖에 있어도 된다고 생각했는데, 아마 iter되면서 heap안의 값들이 모두 answer에 추가 될 것이라고 생각했나보다. 사실은 한번밖에 heappop이 없으니 값이 하나밖에 추가되는게 당연.

  • 구해야 하는 것: index
    그런데 이 index는 items의 배열에서 파생되는 것이니, enumerate()를 이용하여 만든다!

배운 것

  1. new_items 를 정의하는 list comprehension.
  2. heapq.heappush(heap, (-a, idx +1)) // set의 형태로 heapq에 push. 여기서 default로 min_heap이기 때문에, 공격력인 a에 -a를 해준다(공격력이 젤 높은 값이 루트에 위치하게 한다)

0개의 댓글