๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
4๏ธโƒฃ Python/Problem Solving

[Python Algorithm] ๊ณ„๋‹จ ์˜ค๋ฅด๊ธฐ BOJ #2579

by seolhee2750 2022. 2. 4.
๋ฌธ์ œ

https://www.acmicpc.net/problem/2579

 

2579๋ฒˆ: ๊ณ„๋‹จ ์˜ค๋ฅด๊ธฐ

๊ณ„๋‹จ ์˜ค๋ฅด๊ธฐ ๊ฒŒ์ž„์€ ๊ณ„๋‹จ ์•„๋ž˜ ์‹œ์ž‘์ ๋ถ€ํ„ฐ ๊ณ„๋‹จ ๊ผญ๋Œ€๊ธฐ์— ์œ„์น˜ํ•œ ๋„์ฐฉ์ ๊นŒ์ง€ ๊ฐ€๋Š” ๊ฒŒ์ž„์ด๋‹ค. <๊ทธ๋ฆผ 1>๊ณผ ๊ฐ™์ด ๊ฐ๊ฐ์˜ ๊ณ„๋‹จ์—๋Š” ์ผ์ •ํ•œ ์ ์ˆ˜๊ฐ€ ์“ฐ์—ฌ ์žˆ๋Š”๋ฐ ๊ณ„๋‹จ์„ ๋ฐŸ์œผ๋ฉด ๊ทธ ๊ณ„๋‹จ์— ์“ฐ์—ฌ ์žˆ๋Š” ์ 

www.acmicpc.net

 

๋‚ด ๋ฌธ์ œ ํ’€์ด
import sys

n = int(sys.stdin.readline())
a = [0]*n # ํ˜„์žฌ ๊ณ„๋‹จ ๋ฐŸ๊ณ , ์ง์ „ ๊ณ„๋‹จ ๋ฐŸ์•˜๋‹ค๊ณ  ํ•  ๋•Œ
b = [0]*n # ํ˜„์žฌ ๊ณ„๋‹จ ๋ฐŸ๊ณ , ์ง์ „ ๊ณ„๋‹จ ๋ฐŸ์ง€ ์•Š์•˜๋‹ค๊ณ  ํ•  ๋•Œ

for i in range(n):
    now = int(sys.stdin.readline())

    if i == 0:
        a[i] = now
        b[i] = now
    elif i == 1:
        a[i] = now + b[i-1]
        b[i] = now
    else:
        a[i] = now + b[i - 1]
        b[i] = now + max(a[i - 2], b[i - 2])

print(max(a[-1], b[-1]))

๐Ÿ‘‰ DP ๋ฌธ์ œ๋กœ, ํ˜„์žฌ ๊ณ„๋‹จ์„ ๋ฐŸ์•˜์„ ๋•Œ, ์ง์ „ ๊ณ„๋‹จ์„ ๋ฐŸ์•˜๋Š”์ง€ ์•ˆ๋ฐŸ์•˜๋Š”์ง€ ๋‚˜๋ˆ  ์ƒ๊ฐํ•ด์ฃผ๋Š”๊ฒŒ ํฌ์ธํŠธ !

  • ๊ณ„๋‹จ์„ ํ•œ ์นธ์”ฉ ์˜ฌ๋ผ๊ฐ€๋ฉด์„œ 'ํ˜„์žฌ' ๊ณ„๋‹จ์„ ๋ฐŸ์•˜์„ ๋•Œ์˜ ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋‹ด์„ a, b ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ค์–ด์ฃผ์—ˆ๋‹ค.
    a๋Š” ์ง์ „ ๊ณ„๋‹จ์„ ๋ฐŸ์•˜๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๊ณ , b๋Š” ์ง์ „ ๊ณ„๋‹จ์„ ๋ฐŸ์ง€ ์•Š์•˜๋‹ค๊ณ  ๊ฐ€์ •ํ•˜๋Š” ๋ฆฌ์ŠคํŠธ์ด๋‹ค.
  • ์ฃผ์–ด์ง„ ์กฐ๊ฑด์— ๋”ฐ๋ฅด๋ฉด, ์ง์ „ ๊ณ„๋‹จ์„ ๋ฐŸ์•˜์„ ๊ฒฝ์šฐ ์ „์ „ ๊ณ„๋‹จ์€ ๋‹น์—ฐํžˆ ๋ฐŸ์ง€ ์•Š์•˜์–ด์•ผ ํ•œ๋‹ค.
    ๋”ฐ๋ผ์„œ a ๋ฆฌ์ŠคํŠธ์—๋Š” 'ํ˜„์žฌ' ๊ณ„๋‹จ์˜ ๊ฐ’๊ณผ b์˜ ์ง์ „ ๋ˆ„์  ๊ฐ’์„ ๋”ํ•ด์ฃผ์—ˆ๋‹ค.
  • ์ง์ „ ๊ณ„๋‹จ์„ ๋ฐŸ์ง€ ์•Š์•˜์„ ๊ฒฝ์šฐ, ์ „์ „ ๊ณ„๋‹จ์€ ๋‹น์—ฐํžˆ ๋ฐŸ์•˜์„ ๊ฒƒ์ด๋‹ค.
    ํ•˜์ง€๋งŒ ์—ฌ๊ธฐ์„œ ์ฃผ์˜ํ•  ์ ์€, ์ „์ „์ „ ๊ณ„๋‹จ์€ ๋ฐŸ์•˜์„ ์ˆ˜๋„ ์žˆ๊ณ  ์•ˆ๋ฐŸ์•˜์„ ์ˆ˜๋„ ์žˆ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค.
    ๋”ฐ๋ผ์„œ b ๋ฆฌ์ŠคํŠธ์˜ ๊ฒฝ์šฐ 'ํ˜„์žฌ' ๊ณ„๋‹จ ๊ฐ’์— ์ „์ „์— ๋ˆ„์ ๋œ a, b ๊ฐ’ ์ค‘์— ๋” ํฐ ๊ฐ’์„ ๊ณจ๋ผ ๋”ํ–ˆ๋‹ค.

 

๐Ÿ’ก ํ”ผ๋“œ๋ฐฑ
  • ์œ„์™€ ๊ฐ™์€ ์œ ํ˜•์˜ DP ๋ฌธ์ œ๋“ค์€, ๊ผญ ์ฐจ๋ก€๋Œ€๋กœ ๋ฐ˜๋ณตํ•˜๋ฉฐ "'ํ˜„์žฌ'๊ฒƒ์„ ํฌํ•จํ•˜๋ฉด"์„ ์ „์ œ๋กœ
    ๋ฌธ์ œ๋ฅผ ํ’€์ดํ•˜๋Š” ๊ฒƒ์„ ๊ธฐ๋ณธ์œผ๋กœ ํ•˜๋ฉด ์ข€ ๋” ์‰ฝ๊ฒŒ ์ ‘๊ทผํ•˜์—ฌ ํ’€ ์ˆ˜ ์žˆ๋Š” ๊ฒƒ ๊ฐ™๋‹ค.

๋Œ“๊ธ€