πŸ’» Algorithm/Python

[Python] μ΄μ½”ν…Œ - 떑볢이 λ–‘ λ§Œλ“€κΈ° (이진탐색)

μ„ μ£Ό 2021. 10. 20. 00:05

문제

 


πŸ‘† 첫 번째 μ‹œλ„ (μ„ ν˜•νƒμƒ‰)

- 이진탐색 파트인 건 μ•Œμ§€λ§Œ μ™œ 이진탐색을 써야 ν•˜λŠ”μ§€ λͺ°λžμŒ

- μ ˆλ‹¨κΈ°μ˜ 높이λ₯Ό κ°€μž₯ κΈ΄ λ–‘μ˜ 길이둜 μ„€μ •ν•˜κ³  1μ”© μ€„μ—¬λ‚˜κ°€λ©΄μ„œ 잘린 λ–‘μ˜ 길이(rest)의 합을 계산

n, m = map(int, input().split())
height = sorted(list(map(int, input().split())), reverse=True)

for i in range(height[0], 0, -1):
    rest = list(map(lambda x: x-i if x>i else 0, height))
    if sum(rest)>=m:
        print(i)
        break

 

✌ 두 번째 μ‹œλ„ (이진탐색)

- λ–‘μ˜ 길이와 μ ˆλ‹¨κΈ°μ˜ λ†’μ΄λŠ” 0λΆ€ν„° 10μ–΅κΉŒμ§€μ˜ μ •μˆ˜ 쀑 ν•˜λ‚˜μ΄λ‹€.
- μ΄λ ‡κ²Œ 큰 탐색 λ²”μœ„λ₯Ό 보면 λ‹¨μˆœνžˆ μ„ ν˜•νƒμƒ‰μ„ μ‚¬μš©ν•˜μ˜€μ„ λ•Œ μ‹œκ°„μ΄ˆκ³Ό νŒμ •μ„ 받을 수 μžˆμœΌλ―€λ‘œ 이진탐색을 λ– μ˜¬λ €μ•Ό ν•œλ‹€.

n, m = map(int, input().split())
height = list(map(int, input().split()))

low = 0
high = max(height)
answer = 0

while (low <= high):
    mid = (low + high) // 2
    rest = list(map(lambda x: x-mid if x>mid else 0, height))
    if sum(rest)<m:
        high = mid - 1
    else:
        answer = mid
        low = mid + 1

print(answer)