ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

๋ฐ˜์‘ํ˜•

์ฒ˜์Œ์— ๋ฌธ์ œ๋ฅผ ์ฝ์—ˆ์„ ๋•Œ ์ด๊ฒŒ ๋ญ”์†Œ๋ฆฐ๊ฐ€ํ–ˆ๋Š”๋ฐ ๊ธˆ๋ฐฉ ์ดํ•ดํ–ˆ๋‹ค. ๋ญ ๋Œ€์ถฉ ์ œ์ผ ํฐ์ˆ˜๋ฅผ ์ค„์ด๋ฉด ๋ฐฐ์ƒ๋น„์šฉ์ด ์ตœ์†Œ๊ฐ€ ๋˜๋‹ˆ๊นŒ ์ œ์ผ ํฐ ์ˆ˜๋ฅผ ๊นŽ๋Š”๊ฒƒ์„ ๋ฐ˜๋ณตํ•ด์•ผํ•œ๋‹ค๊ณ  ์ƒ๊ฐํ•จ

def solution(no, works):
    result = 0

    # ์ œ์ผ ํฐ ์ˆ˜๋ฅผ ์ผํ•ด์•ผ์ง€ ๋น„์šฉ์ด ์ตœ์†Œํ™”๊ฐ€ ๋œ๋‹ค. -> ํฐ ์ˆ˜๋ฅผ ๊นŽ์•„์•ผํ•จ
    while no > 0 :
        works.sort()
        works[-1] -= 1
        no -= 1
        
    for n, i in enumerate(works):
        works[n] = i*i

    return sum(works)

ใ…œใ…œ

 

def solution(no, works):
    result = 0

    # ์ œ์ผ ํฐ ์ˆ˜๋ฅผ ์ผํ•ด์•ผ์ง€ ๋น„์šฉ์ด ์ตœ์†Œํ™”๊ฐ€ ๋œ๋‹ค. -> ํฐ ์ˆ˜๋ฅผ ๊นŽ์•„์•ผํ•จ
    while no > 0 :
        works.sort()
        if works[-1] == 0:
            break
        works[-1] -= 1
        no -= 1
        
    for n, i in enumerate(works):
        works[n] = i*i

    return sum(works)

์ œ์ผ ํฐ ์ˆ˜์— ๊น์„ ์ž‘์—…์ด ์—†์„ ๋•Œ๋ฅผ ๊ณ ๋ ค๋ฅผ ์•ˆํ•ด์„œ ํ…Œ์ŠคํŠธ์— ํ†ต๊ณผ ๋ชปํ•œ๋“ฏ! ๊ณ ์ณ์คฌ๋”๋‹ˆ ํ†ต๊ณผํ•จ ๋ฃฐ๋ฃจ

 

 

 

์ฝ”๋“œ ๋ฆฌ๋ทฐ

  • ๋ฐฐ์ƒ ๋น„์šฉ ์ตœ์†Œํ™” ๋ฌธ์ œ๋Š” ์šฐ์„  ์ˆœ์œ„ ํ๋ฅผ ์‚ฌ์šฉํ•ด ํ‘ธ๋Š” ๊ฒƒ์ด ์ •์„
  • ๊ฐ€์ง€์น˜๊ธฐ
  • list comprehension์„ ์ด์šฉ

๊ฐ€์ง€์น˜๊ธฐ๊ฐ€ ๋ญ”๊ฐ€,,

 

 

์šฐ์„  ์ˆœ์œ„ ํ

heapq๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ ์ƒ์„ฑํ•  ์ˆ˜ ์žˆ๋‹ค.

import heapq

์ฒซ๋ฒˆ์งธ ์ธ์ž๋Š” heap ์ž์ฒด์ธ list์ด๊ณ , ๋‘๋ฒˆ์งธ ์ธ์ž๋Š” ํŠœํ”Œ์ธ๋ฐ ํŠœํ”Œ์˜ ์ฒซ๋ฒˆ์งธ ์š”์†Œ๋Š” ์šฐ์„ ์ˆœ์œ„ ๊ฐ’, ๋‘๋ฒˆ์งธ ์š”์†Œ๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ๋„ฃ์–ด์ฃผ๋ฉด ๋œ๋‹ค. ํ•จ์ˆ˜์˜ ๋‘๋ฒˆ์งธ ์ธ์ž๋ฅผ ํŠœํ”Œ์ด ์•„๋‹Œ ์ผ๋ฐ˜ ๊ฐ’์„ ๋„ฃ์–ด์ฃผ๋ฉด, ๊ฐ’์„ ๊ธฐ์ค€์œผ๋กœ heap์„ ๋งŒ๋“ค์–ด์ค€๋‹ค. ํŒŒ์ด์ฌ์ด ์ œ๊ณตํ•˜๋Š” ํž™์€ ์ตœ์†Œํž™์ด๋ฏ€๋กœ ์ฃผ์˜ํ•˜๋„๋กํ•˜๊ณ  ์‚ฝ์ž… ๋ณ„ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” O(logN)์ด๋‹ค.

 

Heap์— ์š”์†Œ ์ถ”๊ฐ€ํ•˜๊ธฐ - heappush(๋ฐฐ์—ด์ด๋ฆ„, (์šฐ์„ ์ˆœ์œ„, ์š”์†Œ))

testheap = []
heapq.heappush(testheap, (3, "์šฐ์„ ์ˆœ์œ„ 3"))
heapq.heappush(testheap, (4, "์šฐ์„ ์ˆœ์œ„ 4"))
heapq.heappush(testheap, (8, "์šฐ์„ ์ˆœ์œ„ 8"))
heapq.heappush(testheap, (1, "์šฐ์„ ์ˆœ์œ„ 1"))
heapq.heappush(testheap, (10, "์šฐ์„ ์ˆœ์œ„ 10"))

 

Heap์— ์š”์†Œ ์‚ญ์ œํ•˜๊ธฐ - heappop(๋ฐฐ์—ด์ด๋ฆ„)

heapq.heappop(heaptest)

 

 

์šฐ์„ ์ˆœ์œ„ ํ๋ฅผ ์‚ฌ์šฉํ•œ ๋ฌธ์ œ ํ’€์ด

import heapq

def pqsolution(no, works):
    if no > sum(works):
        return 0
    else:
        # ํฐ ๊ฐ’์ด ์šฐ์„  ์ˆœ์œ„๊ฐ€ ๋†’์•„์•ผํ•˜๋‹ˆ๊นŒ -๋ฅผ ๋ถ™์—ฌ์„œ ์šฐ์„ ์ˆœ์œ„๋ฅผ ๋‹ด๋Š”๋‹ค.
        works = [(-i, i) for i in works]
        heapq.heapify(works) # ํž™์œผ๋กœ ๋งŒ๋“ค๊ธฐ (์šฐ์„ ์ˆœ์œ„์— ๋”ฐ๋ผ ์ •๋ ฌ๋จ)
        print("์šฐ์„ ์ˆœ์œ„ ํ: {}".format(works))

        for _ in range(no):
            # ์ œ์ผ ํฐ ๊ฐ’์ด ๋ฃจํŠธ์— ์žˆ์œผ๋‹ˆ ๊บผ๋ƒ„
            # ๋ฃจํŠธ ๊บผ๋‚ด์„œ ์šฐ์„ ์ˆœ์œ„ ๋ง๊ณ  ๊ฐ’ -1์„ ํ•ด์ค€๋‹ค.
            work = heapq.heappop(works)[1] - 1

            # ์ผ์„ ํ•œ ํ›„ ๋‹ค์‹œ ์šฐ์„ ์ˆœ์œ„ ํ์— ์ €์žฅ
            heapq.heappush(works, (-work, work))

        return sum(i[1] ** 2 for i in works)

 

๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€