[Algo] Programmers PCCP 모의고사 2회 2번 신입사원 교육

heeeeeeeee·2025년 5월 1일

Algorithm

목록 보기
7/14

Sol 1 : 단순 구현

def solution(ability, number):
    answer = 0
    
    k = 0
    while k < number:
        ability.sort()
        ability_sum = ability[0] + ability[1]
        ability[0], ability[1] = ability_sum, ability_sum
        
        k += 1

    answer = sum(ability)
    return answer
  • 단순히 ability 배열 sort하고, 앞에 두 수 더해서 ability 업데이트 해주길 numbers 만큼 반복
  • 입력 수 범위가 엄청 커서 시간 초과...!

Sol 2 : heapq 이용

  • 자동 정렬 된다
  • ability를 queue에 heappush -> 자동 정렬
  • 앞에 두개 heappop하고 -> 다시 heappush -> 알아서 자동 정렬
import heapq

def solution(ability, number):
    queue = []

    for a in ability:
        heapq.heappush(queue,a) # 자동 정렬

    for n in range(number):
        x = heapq.heappop(queue)
        y = heapq.heappop(queue)
        x_y = x+y
        heapq.heappush(queue,x_y)
        heapq.heappush(queue,x_y)

    answer = sum(queue)
    print(heapq.heappop())
    return answer

0개의 댓글