ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

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

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

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

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

 

  1. ๊ณ„๋‹จ์€ ํ•œ ๋ฒˆ์— ํ•œ ๊ณ„๋‹จ์”ฉ ๋˜๋Š” ๋‘ ๊ณ„๋‹จ์”ฉ ์˜ค๋ฅผ ์ˆ˜ ์žˆ๋‹ค.
  2. ์—ฐ์†๋œ ์„ธ ๊ฐœ์˜ ๊ณ„๋‹จ์„ ๋ชจ๋‘ ๋ฐŸ์•„์„œ๋Š” ์•ˆ๋œ๋‹ค.
  3. ๋งˆ์ง€๋ง‰ ๋„์ฐฉ ๊ณ„๋‹จ์€ ๋ฐ˜๋“œ์‹œ ๋ฐŸ์•„์•ผ ํ•œ๋‹ค.

 ๋”ฐ๋ผ์„œ ์ด ๋ฌธ์ œ๋Š” ๊ฒฝ์šฐ์˜ ์ˆ˜๋ฅผ ๋ป—์–ด ๊ฐ€๋Šฅํ•œ ๊ฒฝ์šฐ ์ค‘ ๊ฐ€์žฅ ํฐ ์ˆ˜๋ฅผ ์ฐพ๋Š” ๋ฌธ์ œ์™€ ๊ฐ™๋‹ค. ๊ณ„๋‹จ์˜ ๊ฐœ์ˆ˜๊ฐ€ 300๊ฐœ ์ดํ•˜์ด๋ฏ€๋กœ `DFS`๋กœ ํ’€๊ฒŒ ๋  ๊ฒฝ์šฐ ๋‹น์—ฐํžˆ ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค. ๋”ฐ๋ผ์„œ `DP`๋กœ ํ’€์–ด์•ผ ํ•œ๋‹ค. `DP`๋กœ ๋ฌธ์ œ๋ฅผ ํ’€๊ธฐ ์œ„ํ•ด์„œ๋Š” ๋‹ค์Œ๊ณผ ๊ฐ™์ด ๋ฌธ์ œ๋ฅผ ์ ‘๊ทผํ•˜๋ฉด ๋œ๋‹ค.

 

  • ์ดˆ๊ธฐ์— ํ™œ์šฉํ•  DP ๊ฐ’์„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ดˆ๊ธฐํ™”ํ•œ๋‹ค.
    • `DP[0] = ์ฒซ ๋ฒˆ์งธ ๊ณ„๋‹จ`
    • `DP[1] = ์ฒซ ๋ฒˆ์งธ ๊ณ„๋‹จ + ๋‘ ๋ฒˆ์งธ ๊ณ„๋‹จ`
    • `DP[2] = max(์ฒซ ๋ฒˆ์งธ ๊ณ„๋‹จ + ์„ธ ๋ฒˆ์งธ ๊ณ„๋‹จ, ์ฒซ ๋ฒˆ์งธ ๊ณ„๋‹จ + ๋‘ ๋ฒˆ์งธ ๊ณ„๋‹จ)`
  • ์ดํ›„ DP[3] ๋ถ€ํ„ฐ๋Š” ์ ํ™”์‹์„ ํ†ตํ•ด ๊ฐ’์„ ๊ณ„์‚ฐํ•  ์ˆ˜ ์žˆ๋‹ค.
    • `DP[N] = ํ˜„์žฌ ๊ณ„๋‹จ + max(์ „ ๊ณ„๋‹จ + ์ „์ „์ „ ๊ณ„๋‹จ, ์ „์ „ ๊ณ„๋‹จ)`
  • ์ตœ๋Œ€ 3์นธ์„ ์—ฐ์†ํ•ด์„œ ๋ฐŸ์„ ์ˆ˜ ์—†์–ด, ํ˜„์žฌ ์นธ์„ ๊ธฐ์ค€์œผ๋กœ ์œ„์™€ ๊ฐ™์€ ์ ํ™”์‹์„ ํ†ตํ•ด ๋‹ต์„ ์ฐพ์„ ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

from sys import stdin


if __name__ == '__main__':
    n = int(stdin.readline())
    stair = [int(stdin.readline()) for _ in range(n)]

    # 3๋ณด๋‹ค ์ž‘์€ ๊ฒฝ์šฐ, ์•„๋ž˜ ๋กœ์ง์€ ์ธ๋ฑ์Šค ์˜ค๋ฅ˜ ๋ฐœ์ƒ
    if n < 3:
        print(sum(stair))
        exit(0)

    dp = [0] * n

    #  dp[0], dp[1], dp[2] ์ดˆ๊ธฐํ™”
    dp[0], dp[1] = stair[0], sum(stair[:2])
    dp[2] = max(stair[1] + stair[2], stair[0] + stair[2])

    for i in range(3, n):
        '''
        ์—ฐ์†ํ•ด์„œ ๋ฐŸ์„ ์ˆ˜ ์—†์œผ๋ฏ€๋กœ
        1. ํ˜„์žฌ ๊ณ„๋‹จ + ์ „ ๊ณ„๋‹จ + ์ „์ „์ „ ๊ณ„๋‹จ
        2. ํ˜„์žฌ ๊ณ„๋‹จ + ์ „์ „ ๊ณ„๋‹จ
        '''
        dp[i] = stair[i] + max(stair[i - 1] + dp[i - 3], dp[i - 2])

    print(dp[-1])
728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€