๋ฐฑ์ค€ & ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/greedy

[๋ฐฑ์ค€ 1931] [greedy] ํšŒ์˜์‹ค ๋ฐฐ์ • โ—

_cactus 2021. 4. 18. 13:57
๋ฐ˜์‘ํ˜•

๐Ÿ’ป ๋ฐฑ์ค€ 1931๋ฒˆ [ํšŒ์˜์‹ค ๋ฐฐ์ •]

 

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

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

www.acmicpc.net

ํ’€์ด)

n = int(input())
lst = sorted([list(map(int,input().split())) for _ in range(n)], key = lambda x : (x[1],x[0]))
cnt = 1
cur = lst[0]
for i in range(1,len(lst)) :
    if lst[i][0] >= cur[1] :
        cnt+=1
        cur = lst[i]
print(cnt)
๋ฉ”๋ชจ๋ฆฌ ์‹œ๊ฐ„ ์–ธ์–ด ์ฝ”๋“œ๊ธธ์ด
57248KB 4308ms Python 3 237B

 

๊ณผ์ •)

๋นจ๋ฆฌ ๋๋‚˜๋Š” ์‹œ๊ฐ„๋Œ€๋กœ ํšŒ์˜๋ฅผ ์ •๋ ฌํ•ด์•ผํ•œ๋‹ค๋Š” ๊ฒƒ์€ ์•Œ์•˜๋‹ค.

์ด์™ธ์— ๋‚ด๊ฐ€ ๋†“์ณค๋˜ ๊ฒƒ์€,

1. ํšŒ์˜๊ฐ€ ๋๋‚˜์ž๋งˆ์ž ๋ฐ”๋กœ ๋‹ค์Œ ํšŒ์˜๊ฐ€ ์‹œ์ž‘ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ

   (์ฆ‰,  current ํšŒ์˜์˜ ๋๋‚˜๋Š” ์‹œ๊ฐ„ = next ํšŒ์˜์˜ ์‹œ์ž‘ ์‹œ๊ฐ„  ์ด์–ด๋„ ๊ฐ€๋Šฅํ•˜๋‹ค๋Š” ๊ฒƒ)

2. ์‹œ์ž‘์‹œ๊ฐ„๊ณผ ๋๋‚˜๋Š” ์‹œ๊ฐ„์ด ๊ฐ™์„ ์ˆ˜ ์žˆ๋‹ค๋Š” ๊ฒƒ (์‚ฌ์‹ค ์ด ์กฐ๊ฑด์€ ๋‚ด ์ฝ”๋“œ์—์„œ ์ด๋ฏธ ํ•ด๊ฒฐ์ด ๋œ ์กฐ๊ฑด์ด์–ด์„œ ๋ฌธ์ œ๋ฅผ ๋งž์ถ”๋Š”๋ฐ ์ง€์žฅ์€ ์—†์—ˆ์Œ)

3. ์ •๋ ฌ์„ ํ•  ๋•Œ, ๋๋‚˜๋Š” ์‹œ๊ฐ„์œผ๋กœ ์ •๋ ฌ์„ ํ•œ ๋‹ค์Œ, ์‹œ์ž‘์‹œ๊ฐ„์œผ๋กœ ํ•œ๋ฒˆ ๋” ์ •๋ ฌํ•ด์ค˜์•ผ ํ•œ๋‹ค๋Š” ๊ฒƒ

   ๋‚˜๋Š” ๋๋‚˜๋Š” ์‹œ๊ฐ„์œผ๋กœ๋งŒ ์ •๋ ฌํ–ˆ์–ด์„œ sorting์‹œ key ํ•จ์ˆ˜๋กœ lambda x : x[1]๋งŒ ์ ์–ด์คฌ์—ˆ์Œ.

   ๊ทธ๋ž˜์„œ ์ถ”๊ฐ€๋กœ ์‹œ์ž‘์‹œ๊ฐ„์ธ x[0]๋„ ์ถ”๊ฐ€ํ•˜์—ฌ lambda x : (x[1], x[0])์œผ๋กœ ๋ฐ”๊ฟ”์คŒ

   ์ด๋ฅผ ํ™•์ธํ•  ์ˆ˜ ์žˆ์—ˆ๋˜ ๋ฐ˜๋ก€ โฌ‡โฌ‡

# ํ‹€๋ฆฐ ์ฝ”๋“œ
n = int(input())
lst = sorted([list(map(int,input().split())) for _ in range(n)], key = lambda x : x[1])
cnt = 1
cur = lst[0]
print(lst)
for i in range(1,len(lst)) :
    if lst[i][0] >= cur[1] :
        print(cur)
        cnt+=1
        cur = lst[i]
print(cur)
print(cnt)

# ์ž…๋ ฅ
# 7
# 2 3
# 1 2
# 1 1
# 0 1
# 0 2
# 2 4
# 3 4
 
# ์ถœ๋ ฅ
# [[1, 1], [0, 1], [1, 2], [0, 2], [2, 3], [2, 4], [3, 4]]
# [1, 1]
# [1, 2]
# [2, 3]
# [3, 4]
# 4
# ์ •๋‹ต ์ฝ”๋“œ
n = int(input())
lst = sorted([list(map(int,input().split())) for _ in range(n)], key = lambda x : (x[1],x[0]))
cnt = 1
cur = lst[0]
print(lst)
for i in range(1,len(lst)) :
    if lst[i][0] >= cur[1] :
        print(cur)
        cnt+=1
        cur = lst[i]
print(cur)
print(cnt)

# ์ž…๋ ฅ
# 7
# 2 3
# 1 2
# 1 1
# 0 1
# 0 2
# 2 4
# 3 4

# ์ถœ๋ ฅ
# [[0, 1], [1, 1], [0, 2], [1, 2], [2, 3], [2, 4], [3, 4]]
# [0, 1]
# [1, 1]
# [1, 2]
# [2, 3]
# [3, 4]
# 5

 

๊ฐœ์ธ์ ์œผ๋กœ greedy ๋ฌธ์ œ ์ค‘์—์„œ ํ•ต์‹ฌ์ด๋ผ๊ณ  ์ƒ๊ฐ๋˜๊ณ , ๋‘๊ณ ๋‘๊ณ  ๋ด๋‘์–ด์•ผ ํ•  ๋ฌธ์ œ๋ผ๊ณ  ์ƒ๊ฐ๋œ๋‹ค

728x90
๋ฐ˜์‘ํ˜•