๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Problem Solving

[Python Algorithm] ๊ฐ•์˜์‹ค ๋ฐฐ์ • BOJ #11000

by seolhee2750 2022. 6. 13.
๋ฌธ์ œ

https://www.acmicpc.net/problem/11000

 

11000๋ฒˆ: ๊ฐ•์˜์‹ค ๋ฐฐ์ •

์ฒซ ๋ฒˆ์งธ ์ค„์— N์ด ์ฃผ์–ด์ง„๋‹ค. (1 ≤ N ≤ 200,000) ์ดํ›„ N๊ฐœ์˜ ์ค„์— Si, Ti๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. (0 ≤ Si < Ti ≤ 109)

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import sys
import heapq

n = int(sys.stdin.readline().strip())
times = [] # ์ž…๋ ฅ๋˜๋Š” ๊ฐ•์˜ ์‹œ๊ฐ„๋“ค์„ ํŠœํ”Œ ํ˜•ํƒœ๋กœ ์ €์žฅ
rooms = [] # ๊ฐ ์›์†Œ๊ฐ€ ํ•˜๋‚˜์˜ ๊ฐ•์˜์‹ค์„ ๋œปํ•˜๋Š” ๋ฐฐ์—ด
for _ in range(n):
    (start, end) = map(int, sys.stdin.readline().strip().split())
    times.append((start, end))
times.sort(key=lambda x: (x[0], x[1])) # ์‹œ์ž‘ ์‹œ๊ฐ„์„ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ, ์‹œ์ž‘์‹œ๊ฐ„์ด ๊ฐ™์„ ๊ฒฝ์šฐ ์ข…๋ฃŒ ์‹œ๊ฐ„ ๊ธฐ์ค€ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ

for i in times:
    (start, end) = i
    if rooms and rooms[0] <= start:
        heapq.heappop(rooms) # rooms์˜ ์ตœ์†Ÿ๊ฐ’ pop
    heapq.heappush(rooms, end) # rooms์— ํ˜„์žฌ ๊ฐ•์˜์˜ ์ข…๋ฃŒ ์‹œ๊ฐ„ push

print(len(rooms))

๐Ÿ‘‰ ์šฐ์„ ์ˆœ์œ„ ํ ๋ฌธ์ œ

  • times ๋ฆฌ์ŠคํŠธ์— ๊ฐ•์˜ ์‹œ๊ฐ„๋“ค์„ ํŠœํ”Œ ํ˜•ํƒœ๋กœ ๋ฐ›๊ณ , ์‹œ์ž‘์‹œ๊ฐ„์„ ๊ธฐ์ค€์œผ๋กœ ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌํ•ด์ฃผ์—ˆ๋‹ค.
  • rooms๋Š” ๊ฐ ์›์†Œ๊ฐ€ ํ•˜๋‚˜์˜ ๊ฐ•์˜์‹ค์„ ๋œปํ•˜๋Š” ๋ฐฐ์—ด์ธ๋ฐ, ๊ฐ•์˜์‹ค๋งˆ๋‹ค ๋๋‚˜๋Š” ์‹œ๊ฐ„์„ ์—…๋ฐ์ดํŠธํ•ด์ฃผ๊ธฐ ์œ„ํ•ด ๋งŒ๋“ค์—ˆ๋‹ค.
  • for๋ฌธ์—์„œ๋Š” rooms ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋น„์–ด์žˆ์ง€ ์•Š๊ณ , ํ˜„์žฌ ๊ฐ•์˜์˜ ์‹œ์ž‘ ์‹œ๊ฐ„์ด rooms์˜ ์ตœ์†Ÿ๊ฐ’๋ณด๋‹ค ์ž‘์„ ๊ฒฝ์šฐ
    rooms์˜ ์ตœ์†Ÿ๊ฐ’์„ ๋บ€ ํ›„ ํ˜„์žฌ ๊ฐ•์˜์˜ ์ข…๋ฃŒ ์‹œ๊ฐ„์„ pushํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ–ˆ๋‹ค.
    => ์ตœ์†Ÿ๊ฐ’์ด ๋“ค์–ด์žˆ๋˜ ๊ฐ•์˜์‹ค์˜ ์ข…๋ฃŒ ์‹œ๊ฐ„์„ ์ƒˆ๋กญ๊ฒŒ ์—…๋ฐ์ดํŠธํ•ด์ฃผ๋Š” ๋ถ€๋ถ„์ด๋‹ค.
  • ์œ„์™€ ๋ฐ˜๋Œ€ ๊ฒฝ์šฐ์—๋Š” ์ƒˆ๋กœ์šด ๊ฐ•์˜์‹ค์ด ํ•„์š”ํ•œ ๊ฒƒ์ด๋ฏ€๋กœ, ๊ทธ๋ƒฅ ํ˜„์žฌ ๊ฐ•์˜ ์ข…๋ฃŒ ์‹œ๊ฐ„์„ pushํ•˜๋Š” ๋™์ž‘๋งŒ ํ•ด์ฃผ์—ˆ๋‹ค.
  • rooms๋Š” ์ด ์‚ฌ์šฉ๋œ ๊ฐ•์˜์‹ค๋“ค์„ ๊ฐ€์ง€๋ฏ€๋กœ, ๊ทธ ๊ธธ์ด๋ฅผ ๊ฒฐ๊ณผ๋กœ ์ถœ๋ ฅํ•ด์ฃผ์—ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • heapq๋ฅผ ์ฒ˜์Œ์จ๋ด์„œ ์˜ค๋ž˜๊ฑธ๋ ธ๋Š”๋ฐ ์ด๋ก ๋„ ๊ฐ™์ด ๊ณต๋ถ€ํ•ด๋ด์•ผ๊ฒ ๋‹ค.

 

๋Œ“๊ธ€