๋ฐฑ์ค€ 11000 ํŒŒ์ด์ฌ

2022. 1. 4. 21:06ใ†๐Ÿ”ฑ Algorithm/Greedy

 

 

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

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

www.acmicpc.net

 

 

 

์ •๋‹ต ์ฝ”๋“œ

from sys import stdin
import heapq

read = stdin.readline

N = int(read())
heap = []
result = []
for _ in range(N):
    a, b = map(int, read().split())
    result.append((a, b))
result.sort() # time ์ •๋ ฌ์ƒํƒœ
heapq.heappush(heap, result[0][1]) # ์ฒซ๋ฒˆ์งธ ์ˆ˜์—… ๋๋‚˜๋Š” ์‹œ๊ฐ„๋ถ€ํ„ฐ ๋“ค์–ด๊ฐ€ ์žˆ๋‹ค.

for i in range(1, N):
    if heap[0] > result[i][0]: # ์‘ ๋ชป๋“ค์–ด๊ฐ€
        heapq.heappush(heap, result[i][1])
    else: # ๋“ค์–ด๊ฐˆ ์ˆ˜ ์žˆ์–ด
        heapq.heappop(heap)
        heapq.heappush(heap, result[i][1])

print(len(heap))

 

 

์˜ค๋‹ต ์ฝ”๋“œ (์‹œ๊ฐ„๋ณต์žก๋„ X)

๋ฌธ์ œ์—์„œ N์ด ์ตœ๋Œ€ 200,000๊นŒ์ง€ ์น˜์†Ÿ์„ ์ˆ˜ ์žˆ๋‹ค๊ณ  ํ–ˆ๋‹ค. ์ด๋Ÿฐ ๊ฒฝ์šฐ์—” ์ค‘์ฒฉ ๋ฐ˜๋ณต๋ฌธ์œผ๋กœ๋Š” ๋‹ต์— ์ ‘๊ทผํ•  ์ˆ˜ ์—†๋‹ค. 

ํ•œ๋ฒˆ์˜ for ๋ฌธ์œผ๋กœ ๋๋‚ด์•ผํ•œ๋‹ค. 

๋‚˜๋Š” ๊ธฐ๊ป heapq ๋กœ heap ์„ ๋งŒ๋“ค์–ด๋†“๊ณ , ๊ทธ ๋‚ด๋ถ€์—์„œ for ๋ฌธ์„ ํ•œ๋ฒˆ ๋” ๋Œ๋ ธ๋‹ค. 

heap[0] ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด, ๊ตณ์ด heapq.heappop()์„ ํ•˜์ง€ ์•Š๋”๋ผ๋„ ์ž์—ฐ์Šค๋Ÿฝ๊ฒŒ ๋‚ด๊ฐ€ ์›ํ•˜๋Š” ๊ฐ’์„ ๋‚˜ํƒ€๋‚ด์–ด ๋น„๊ตํ•  ์ˆ˜ ์žˆ๋‹ค.

-

while heap ์„ ์กฐ๊ฑด์œผ๋กœ ํ•˜์—ฌ, heap ์„ ๋ชจ๋‘ ์†Œ์ง„ํ•  ๋•Œ๊นŒ์ง€ ๋น„๊ต๋ฅผ ์ง„ํ–‰ํ–ˆ๋‹ค. ๊ทธ๋Ÿฌ๊ณ ์„  result ๋ฆฌ์ŠคํŠธ์˜ ๊ธธ์ด๋กœ ๋‹ต์„ ๊ตฌํ•˜๋ คํ–ˆ๋‹ค.

๋ฐ˜๋ฉด ์ •๋‹ต ์ฝ”๋“œ์—์„  heap ์˜ ๊ธธ์ด๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ •๋‹ต ์ฝ”๋“œ๋ฅผ ๊ตฌํ–ˆ๋‹ค. ์ด ๋ถ€๋ถ„์ด ์ •๋‹ต๊ณผ ๊ฐ€์žฅ ํฐ ์ฐจ์ด์˜€๋‹ค. 

from sys import stdin
import heapq

read = stdin.readline

N = int(read())
heap = []
result = []

for _ in range(N):
    a, b = map(int, read().split())
    heapq.heappush(heap, (a, b))
start, end = heapq.heappop(heap)
result.append([end])

while heap:
    pops = heapq.heappop(heap)
    for i in range(len(result)):
        if result[i][-1] <= pops[0]:
            result[i].append(pops[1])
            break
    else:
        result.append([pops[1]])


print(len(result))