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

2022. 1. 5. 07:06ใ†๐Ÿ”ฑ Algorithm/Greedy

 

1931๋ฒˆ: ํšŒ์˜์‹ค ๋ฐฐ์ •

(1,4), (5,7), (8,11), (12,14) ๋ฅผ ์ด์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

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 = sorted(result, key=lambda x: x[0])
result = sorted(result, key=lambda x: x[1])

count, last = 0, 0
for start, end in result:
    if start >= last:
        count += 1
        last = end
print(count)

1. ์‹œ์ž‘ ์‹œ๊ฐ„์„ ๊ธฐ์ค€์œผ๋กœ ๋จผ์ € ์ •๋ ฌํ•œ๋‹ค.

๊ทธ๋ ‡๊ฒŒ ๋˜๋ฉด ๋จผ์ € ์‹œ์ž‘ํ•˜๋Š” ๊ฐ•์˜ ๋ถ€ํ„ฐ ์ •๋ ฌ๋œ๋‹ค. ๋๋‚˜๋Š” ์‹œ๊ฐ„์€ ๋ณด์žฅ๋˜์ง€ ๋ชปํ•œ๋‹ค.

 

2. ๋๋‚˜๋Š” ์‹œ๊ฐ„์„ ๊ธฐ์ค€์œผ๋กœ ๋‹ค์‹œ ์ •๋ ฌํ•œ๋‹ค.

๊ทธ๋ ‡๊ฒŒ ๋˜๋ฉด ์ด๋ฏธ ์‹œ์ž‘ ์‹œ๊ฐ„์„ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌ์ด ๋œ ์ƒํƒœ์—์„œ, ๋‹ค์‹œ ๋๋‚˜๋Š” ์‹œ๊ฐ„์œผ๋กœ ์ •๋ ฌ๋œ๋‹ค.

๋งŒ์•ฝ ์˜ˆ์‹œ๋กœ (4, 4) ์™€ (1, 4) ๊ฐ€ ์žˆ๋‹ค๋ฉด, ์‹œ์ž‘ ์‹œ๊ฐ„์„ ๊ธฐ์ค€์œผ๋กœ ๋จผ์ € ์ •๋ ฌ์„ ํ•ด์•ผ, ๋ฌธ์ œ์— ์˜๋„๋Œ€๋กœ ์ •๋ ฌํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋œ๋‹ค.

 

์˜ค๋‹ต ์ฝ”๋“œ

์†ŒํŒ… ๊ณผ์ •์—์„œ ๋žŒ๋‹ค๋ฅผ ์ด์šฉํ–ˆ๋‹ค.

์ฒ˜์Œ์—๋Š” ๋žŒ๋‹ค์‹์œผ๋กœ ์‹œ์ž‘ ์‹œ๊ฐ„๊ณผ ์ข…๋ฃŒ ์‹œ๊ฐ„์„ ๋™์‹œ์— ์ •๋ ฌํ•˜๋ ค๊ณ  ํ–ˆ๋‹ค.

result = sorted(result, key=lambda x: (x[0], x[1]))  # ์œ„์˜ ๋‘ ๋ผ์ธ๊ณผ ์ด ๋ผ์ธ์€ ์—„์—ฐํžˆ ๋‹ค๋ฅด๋‹ค.

 ์œ„ ์ฝ”๋“œ์˜ ๋ฌธ์ œ๋Š” ์‹œ์ž‘ ์‹œ๊ฐ„๊ณผ ์ข…๋ฃŒ ์‹œ๊ฐ„์„ ๋ชจ๋‘ ๊ธฐ์ค€์œผ๋กœ ์ •๋ ฌํ•œ๋‹ค๋Š” ์ ์ด๋‹ค. (์‚ฌ์‹ค ์ฒซ๋ฒˆ์งธ ์›์†Œ๋กœ๋งŒ ์ •๋ ฌ๋œ๋‹ค.)

 

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 = sorted(result, key=lambda x: (x[0], x[1])) ์œ„์˜ ๋‘ ๋ผ์ธ๊ณผ ์ด ๋ผ์ธ์€ ์—„์—ฐํžˆ ๋‹ค๋ฅด๋‹ค.

count, last = 0, 0
for start, end in result:
    if start >= last:
        count += 1
        last = end
print(count)