λ°±μ€€ 1374 κ°•μ˜μ‹€ 파이썬 (damn pythonic)

2023. 1. 27. 00:57γ†πŸ”± Algorithm/Greedy

μ „ν˜•μ μΈ 그리디 μ•Œκ³ λ¦¬μ¦˜μ΄λ‹€

 

1374번: κ°•μ˜μ‹€

첫째 쀄에 κ°•μ˜μ˜ 개수 N(1 ≤ N ≤ 100,000)이 주어진닀. λ‘˜μ§Έ 쀄뢀터 N개의 쀄에 걸쳐 각 μ€„λ§ˆλ‹€ μ„Έ 개의 μ •μˆ˜κ°€ μ£Όμ–΄μ§€λŠ”λ°, μˆœμ„œλŒ€λ‘œ κ°•μ˜ 번호, κ°•μ˜ μ‹œμž‘ μ‹œκ°„, κ°•μ˜ μ’…λ£Œ μ‹œκ°„μ„ μ˜λ―Έν•œλ‹€. κ°•μ˜

www.acmicpc.net

 

⭐️ 풀이

λ‹€λ₯Έ λΆ„λ“€ 풀이 λ³΄λ‹ˆκΉŒ heapq λ₯Ό μ‚¬μš©ν–ˆλ˜λ°, λ‚˜λŠ” 리슀트λ₯Ό μ‚¬μš©ν–ˆλ‹€.

 

1. κ°€μž₯ λ¨Όμ € μ‹œμž‘ν•˜λŠ” κ°•μ˜ κΈ°μ€€μœΌλ‘œ μ •λ ¬ μΉœλ‹€.

2. μ°¨λ‘€λŒ€λ‘œ λ¦¬μŠ€νŠΈμ— μ €μž₯ν•˜λ˜, λλ‚˜λŠ” μ‹œκ°„λ§Œ μ €μž₯ν•œλ‹€.

3. κ°•μ˜λ₯Ό μ°¨λ‘€λ‘œ 순회 -> λ¦¬μŠ€νŠΈμ— μ €μž₯된 μˆ˜λ³΄λ‹€ κ°•μ˜ μ‹œμž‘ μ‹œκ°„μ΄ 더 크닀면, μ €μž₯된 μΈλ±μŠ€μ— λλ‚˜λŠ” μ‹œκ°„μ„ μ €μž₯ν•œλ‹€.

(이전 κ°•μ˜ λλ‚˜λŠ” μ‹œκ°„ < λ‹€μŒ κ°•μ˜ μ‹œμž‘μ‹œκ°„ : κ°•μ˜μ‹€ μ‚¬μš© κ°€λŠ₯)

 

κ°•μ˜μ‹€ ꡐ체가 ν•„μš”ν•  λ•Œ del μ΄λ‚˜ remove λ₯Ό 칠까 생각도 ν–ˆλŠ”λ°, ν•΄λ‹Ή 인덱슀의 κ°’λ§Œ λ°”κΏ”μ£Όλ©΄ 더 κ°„λ‹¨νžˆ ν’€ 수 μžˆλ‹€.

 

🌿 κΈ°μ‘΄ μ½”λ“œ

N = int(input())
temp = []
result = []

for _ in range(N):
    a, b, c = map(int, input().split())
    temp.append([b, c])
temp.sort(key=lambda x: x[0])
flag = True

for t in temp:
    start, end = t
    if len(result) == 0:
        result.append(end)
        continue
    for idx, r in enumerate(result):
        if r <= start:
            result[idx] = end
            flag = False
            break
    if flag:
        result.append(end)
    flag = True
print(len(result))

 

 

⚑️ κ°œμ„ λœ μ½”λ“œ

파이썬 μ§„μ§œ μ‹ νƒœν‹± μŠˆκ°€ 쩐당 γ…‹

flag 둜 괜히 λΆ„κΈ° μΉ˜μ§€μ•Šκ³  for~else μ‚¬μš©ν–ˆλ‹€. 개꾸λ₯΄

N = int(input())

times = sorted([list(map(int, input().split())) for _ in range(N)], key=lambda x: x[1])
result = [times[0][2]]

for i, start, end in times[1:]:
    for idx, r in enumerate(result):
        if r <= start:
            result[idx] = end
            break
    else:
        result.append(end)

print(len(result))

 

 

βž• Heapq λ₯Ό μ‚¬μš©ν•œ 풀이

import heapq

N = int(input())
times = sorted([list(map(int, input().split())) for _ in range(N)], key=lambda x: x[1])
min_heap = []
count = 0
for i, start, end in times:
    while min_heap and min_heap[0] <= start:
        heapq.heappop(min_heap)
    heapq.heappush(min_heap, end)
    count = max(count, len(min_heap))

print(count)

heapq λ₯Ό μ‚¬μš©ν•œ 풀이가 μ›”λ“±νžˆ λΉ λ₯Έ 것을 확인할 수 μžˆλ‹€.

list λ₯Ό μ‚¬μš©ν•  땐 for 문이 break λ˜μ§€ μ•ŠλŠ” 이상 result λ₯Ό λͺ¨λ‘ μˆœνšŒν•΄μ•Ό ν•œλ‹€. λ”°λΌμ„œ heapq 에 λΉ„ν•΄ μ‹œκ°„μ΄ 많이 μ†Œμš”λ  수 밖에 μ—†λ‹€.