๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/๋ฐฑ์ค€

[๋ฐฑ์ค€] #2805 ๋‚˜๋ฌด ์ž๋ฅด๊ธฐ (Python)

1. ๋ฌธ์ œ ์„ค๋ช…

๋ฌธ์ œ ๋งํฌ

  • ์ž…๋ ฅ :
    • ์ฒซ์งธ ์ค„์— ๋‚˜๋ฌด์˜ ์ˆ˜ N๊ณผ ์ƒ๊ทผ์ด๊ฐ€ ์ง‘์œผ๋กœ ๊ฐ€์ ธ๊ฐ€๋ ค๊ณ  ํ•˜๋Š” ๋‚˜๋ฌด์˜ ๊ธธ์ด M
    • ๋‘˜์งธ ์ค„์—๋Š” ๋‚˜๋ฌด์˜ ๋†’์ด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค.
  • ์ถœ๋ ฅ :์ ์–ด๋„ M๋ฏธํ„ฐ์˜ ๋‚˜๋ฌด๋ฅผ ์ง‘์— ๊ฐ€์ ธ๊ฐ€๊ธฐ ์œ„ํ•ด์„œ ์ ˆ๋‹จ๊ธฐ์— ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋Š” ๋†’์ด์˜ ์ตœ๋Œ“๊ฐ’์„ ์ถœ๋ ฅ

2. ์ฝ”๋“œ

solution1.py

# -*- coding: utf-8 -*-
import sys
input = sys.stdin.readline

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

start = 0
end = max(tree)
result = 0
while start <= end:
    mid = (start + end) //2
    #h๊ธฐ์ค€์œผ๋กœ ์ž๋ฅธ ํ›„ ๊ฐ€์ ธ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๋‚˜๋ฌด ๊ธธ์ด total
    total = 0
    for i in range(n):
        if tree[i] > mid:
            total += tree[i] - mid

    if total == m:
        result = mid
        break
    elif total < m : #๋‚˜๋ฌด๊ธธ์ด๊ฐ€ ๋ถ€์กฑํ•˜๋ฉด mid๋ฅผ ์•ž์ชฝ์œผ๋กœ
        end = mid-1

    else: #๋‚˜๋ฌด์–‘์ด ์ถฉ๋ถ„ํ•˜๋ฉด ์ €์žฅ
        start = mid+1
        result = mid

print(result)

solution2.py

# -*- coding: utf-8 -*-
import sys
input = sys.stdin.readline

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

start = 0
end = max(tree)
result = 0
while start <= end:
    mid = (start + end) //2
    #h๊ธฐ์ค€์œผ๋กœ ์ž๋ฅธ ํ›„ ๊ฐ€์ ธ๊ฐˆ ์ˆ˜ ์žˆ๋Š” ๋‚˜๋ฌด ๊ธธ์ด total
    total = 0
    for i in range(n):
        if tree[i] > mid:
            total += tree[i] - mid

    if total < m : #๋‚˜๋ฌด๊ธธ์ด๊ฐ€ ๋ถ€์กฑํ•˜๋ฉด mid๋ฅผ ์•ž์ชฝ์œผ๋กœ
        end = mid-1

    else: #๋‚˜๋ฌด์–‘์ด ์ถฉ๋ถ„ํ•˜๋ฉด ์ €์žฅ
        start = mid+1
        result = mid

print(result)

3. ํšŒ๊ณ 

  • ๋‚˜๋ฌด์˜ ๋†’์ด๊ฐ€ 1,000,000,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™์€ ์–‘์˜ ์ •์ˆ˜ ๋˜๋Š” 0์ด๊ธฐ ๋•Œ๋ฌธ์— ์ด์ง„ํƒ์ƒ‰์„ ์‚ฌ์šฉํ•ด์„œ ํƒ์ƒ‰์‹œ๊ฐ„์„ ์ค„์—ฌ์•ผํ•œ๋‹ค.
  • ๋ชฉ์žฌ ์ ˆ๋‹จ๊ธฐ ๋†’์ด๋ฅผ mid๋กœ ๋ณด๊ณ  start์™€ end์˜ ์ค‘๊ฐ„๊ฐ’์œผ๋กœ ์„ค์ •ํ•œ๋‹ค. (์ดˆ๊ธฐ start=0, end=max(tree))
  • ์ ˆ๋‹จ๊ธฐ ๋†’์ด mid๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ž˜๋ž์„ ๋•Œ ์–ป์„ ์ˆ˜ ์žˆ๋Š” ๋‚˜๋ฌด์˜ ๊ธธ์ด๋ฅผ total์— ์ €์žฅํ•œ๋‹ค.
  • ๊ฐ€์ ธ๊ฐ€๊ธธ ์›ํ–ˆ๋˜ ๊ธธ์ด m๊ณผ ๋น„๊ตํ•˜์—ฌ ๊ธธ์ด๊ฐ€ ๊ฐ™์œผ๋ฉด result์— mid๋ฅผ ์ €์žฅ,
  • ๋‚˜๋ฌด์˜ ๊ธธ์ด๊ฐ€ ๋ถ€์กฑํ•˜๋ฉด ๋” ์ž‘์€ ์ ˆ๋‹จ๊ธฐ ๊ธฐ์ค€(mid)๋กœ ์‚ดํŽด๋ด์•ผํ•˜๋ฏ€๋กœ, end = mid-1ํ•˜์—ฌ ํ˜„์žฌ๋ณด๋‹ค ์ž‘์€์ ˆ๋‹จ๊ธฐ ๊ธฐ์ค€์œผ๋กœ ๋‚˜๋ฌด๋ฅผ ์ž๋ฅด๋„๋ก ํ•œ๋‹ค.
  • ๋‚˜๋ฌด์˜ ๊ธธ์ด ์ถฉ๋ถ„ํ•˜๋ฉด ์ผ๋‹จ start= mid+1๋ฅผ ํ†ตํ•ด ์˜ค๋ฅธ์ชฝ๋„ ํƒ์ƒ‰ํ•  ์—ฌ์ง€๋ฅผ ๋‚จ๊ฒจ๋‘๊ณ , result์—๋Š” mid๋ฅผ ์ €์žฅํ•œ๋‹ค. (์ตœ๋Œ€ํ•œ m๊ณผ ๋น„์Šทํ•œ ๊ธธ์ด์˜ ๋‚˜๋ฌด๋ฅผ ๋‹ด๋Š” ๊ฒƒ์ด ์ค‘์š”ํ•˜๋ฏ€๋กœ, ํ›„๋ณด๊ฐ€ ์ƒ๊ธฐ๋ฉด ์ผ๋‹จ ์ €์žฅ, ์ด์ง„ํƒ์ƒ‰์„ ํ•˜๋ฉฐ m๊ณผ ๋” ๊ฐ€๊นŒ์šด ์ˆ˜๋กœ update)
  • PyPy3๋กœ ์ œ์ถœํ•ด์•ผ ์‹œ๊ฐ„์ดˆ๊ณผ๊ฐ€ ์•ˆ๋‚œ๋‹ค.
    • solution1.py : 273888KB, 580ms
    • solution2.py : 273884KB, 356ms