๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐˜ผ๐™ก๐™œ๐™ค๐™ง๐™ž๐™ฉ๐™๐™ข/๐™‹๐™ง๐™ค๐™œ๐™ง๐™–๐™ข๐™ข๐™š๐™ง๐™จ

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ํƒ์š•๋ฒ•(greedy) '์ฒด์œก๋ณต' ํŒŒ์ด์ฌ ํ’€์ด

by beomcoder 2023. 2. 19.
728x90
๋ฐ˜์‘ํ˜•
 

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

"""
์ ์‹ฌ์‹œ๊ฐ„์— ๋„๋‘‘์ด ๋“ค์–ด, ์ผ๋ถ€ ํ•™์ƒ์ด ์ฒด์œก๋ณต์„ ๋„๋‚œ๋‹นํ–ˆ์Šต๋‹ˆ๋‹ค. 
๋‹คํ–‰ํžˆ ์—ฌ๋ฒŒ ์ฒด์œก๋ณต์ด ์žˆ๋Š” ํ•™์ƒ์ด ์ด๋“ค์—๊ฒŒ ์ฒด์œก๋ณต์„ ๋นŒ๋ ค์ฃผ๋ ค ํ•ฉ๋‹ˆ๋‹ค. 
ํ•™์ƒ๋“ค์˜ ๋ฒˆํ˜ธ๋Š” ์ฒด๊ฒฉ ์ˆœ์œผ๋กœ ๋งค๊ฒจ์ ธ ์žˆ์–ด, ๋ฐ”๋กœ ์•ž๋ฒˆํ˜ธ์˜ ํ•™์ƒ์ด๋‚˜ 
๋ฐ”๋กœ ๋’ท๋ฒˆํ˜ธ์˜ ํ•™์ƒ์—๊ฒŒ๋งŒ ์ฒด์œก๋ณต์„ ๋นŒ๋ ค์ค„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
์˜ˆ๋ฅผ ๋“ค์–ด, 4๋ฒˆ ํ•™์ƒ์€ 3๋ฒˆ ํ•™์ƒ์ด๋‚˜ 5๋ฒˆ ํ•™์ƒ์—๊ฒŒ๋งŒ ์ฒด์œก๋ณต์„ ๋นŒ๋ ค์ค„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

์ฒด์œก๋ณต์ด ์—†์œผ๋ฉด ์ˆ˜์—…์„ ๋“ค์„ ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— ์ฒด์œก๋ณต์„ ์ ์ ˆํžˆ ๋นŒ๋ ค 
์ตœ๋Œ€ํ•œ ๋งŽ์€ ํ•™์ƒ์ด ์ฒด์œก์ˆ˜์—…์„ ๋“ค์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.
์ „์ฒด ํ•™์ƒ์˜ ์ˆ˜ n, ์ฒด์œก๋ณต์„ ๋„๋‚œ๋‹นํ•œ ํ•™์ƒ๋“ค์˜ ๋ฒˆํ˜ธ๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด lost, 
์—ฌ๋ฒŒ์˜ ์ฒด์œก๋ณต์„ ๊ฐ€์ ธ์˜จ ํ•™์ƒ๋“ค์˜ ๋ฒˆํ˜ธ๊ฐ€ ๋‹ด๊ธด ๋ฐฐ์—ด reserve๊ฐ€ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ฃผ์–ด์งˆ ๋•Œ,
์ฒด์œก์ˆ˜์—…์„ ๋“ค์„ ์ˆ˜ ์žˆ๋Š” ํ•™์ƒ์˜ ์ตœ๋Œ“๊ฐ’์„ return ํ•˜๋„๋ก solution ํ•จ์ˆ˜๋ฅผ ์ž‘์„ฑํ•ด์ฃผ์„ธ์š”.
"""

def solution(n, lost, reserve):
    student = [1 for _ in range(n)]
    for l in lost:
        student[l-1] -= 1
    for r in reserve:
        student[r-1] += 1
    student = [1] + student + [1]
    
    for i in range(1, n+1):
        if student[i] == 2:
            if student[i-1] == 0:
                student[i-1] = 1
                student[i] = 1
            elif student[i+1] == 0:
                student[i+1] = 1
                student[i] = 1
    return n - student.count(0)
    
"""
์ตœ๋Œ€ํ•œ ์ง๊ด€์ ์œผ๋กœ ํ’€์–ด๋ณด๋ ค๊ณ  ํ–ˆ๋‹ค. 
๋จผ์ € student๋Š” ์ „๋ถ€ ์ฒด์œก๋ณต์ด 1๋ฒŒ์”ฉ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ–ˆ๋‹ค.
๊ทธ๋ฆฌ๊ณ  ์žƒ์–ด๋ฒ„๋ฆฐ ์‚ฌ๋žŒ๊ณผ ์—ฌ๋ถ„์ด ์žˆ๋Š” ์‚ฌ๋žŒ์€ -1, +1์„ ๊ฐ๊ฐ ํ•ด์ฃผ์—ˆ๋‹ค.

๊ทธ๋‹ค์Œ ๋กœ์ง์—์„œ ํ•™์ƒ์˜ ์•ž๊ณผ ๋’ค๋ฅผ ํ™•์ธํ•˜๋Š” ๊ฒƒ์œผ๋กœ ์งฐ๊ธฐ ๋•Œ๋ฌธ์—
์ฒซ๋ฒˆ์งธ ์‚ฌ๋žŒ ์•ž์— ์ž„์˜๋กœ 1, ๋งˆ์ง€๋ง‰ ์‚ฌ๋žŒ ๋’ค์— ์ž„์˜๋กœ 1์„ ๋„ฃ์–ด์ฃผ์—ˆ๋‹ค.

๊ทธ๋ฆฌ๊ณ  for๋ฌธ์„ ๋Œ๋ฉด์„œ ๊ทธ ํ•™์ƒ์ด ์—ฌ๋ถ„์˜ ์ฒด์œก๋ณต์ด ์žˆ์„๋•Œ
์•ž์‚ฌ๋žŒ๊ณผ ๋’ท์‚ฌ๋žŒ์ด ์ฒด์œก๋ณต์ด ์—†์„ ๊ฒฝ์šฐ ๋‚˜๋ˆ ์ค€๋‹ค.

์•ž์‚ฌ๋žŒ์„ ๋จผ์ € ํ™•์ธํ•˜๋Š” ์ด์œ ๋Š” ๋’ท์‚ฌ๋žŒ์€ ๊ทธ ๋‹ค์Œ์‚ฌ๋žŒ์ด ์ค„์ˆ˜๋„ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.
๊ทธ๋ฆฌ๊ณ  ์ „์ฒดํ•™์ƒ์ˆ˜ n์—์„œ ์ฒด์œก๋ณต์ด ์—†๋Š” 0์„ ๋นผ์ฃผ๋ฉด ์ตœ๋Œ€ ์‚ฌ๋žŒ์ˆ˜๊ฐ€ ๋‚˜์˜จ๋‹ค.
"""
728x90
๋ฐ˜์‘ํ˜•

๋Œ“๊ธ€