๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 2096 - ๋‚ด๋ ค๊ฐ€๊ธฐ

by HandHand 2021. 3. 18.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 2096๋ฒˆ

ํ’€์ด ๊ณผ์ •

์ „ํ˜•์ ์ธ DP ๋ฌธ์ œ์ด์ง€๋งŒ ๋ฉ”๋ชจ๋ฆฌ ์ œํ•œ์ด ๋นก์…‰๋‹ˆ๋‹ค.
์Šฌ๋ผ์ด๋”ฉ ์œˆ๋„์šฐ ๋ฅผ ํ™œ์šฉํ•ด์„œ memo 2์ฐจ์› ๋ฐฐ์—ด์„ 2 * 3 ์˜ ํฌ๊ธฐ๋กœ ์ง€์ •ํ•ด์„œ ๊ฐ’์„ ๊ตฌํ•˜๋ฉด ๋˜๋Š”๋ฐ
๋ฌธ์ œ๋Š” ์ฒ˜์Œ์— top-down ๋ฐฉ์‹์œผ๋กœ ์ ‘๊ทผํ–ˆ๋‹ค๊ฐ€ board ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋ฅผ ์ค„์ผ ๋ฐฉ๋ฒ•์ด ์—†์–ด์„œ ๊ณ„์† ๋ฉ”๋ชจ๋ฆฌ ์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค.
๋Œ€์‹ ์— bottom-up ๋ฐฉ์‹์œผ๋กœ ๋ณ€๊ฒฝํ•˜๊ณ  board ๋ฅผ ๋ฏธ๋ฆฌ ์ž…๋ ฅ ๋ฐ›๋Š” ๊ฒƒ์ด ์•„๋‹ˆ๋ผ
ํ•œ ์ค„์”ฉ ์ž…๋ ฅ ๋ฐ›์•„์„œ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์œผ๋กœ ๋ณ€๊ฒฝํ•˜์—ฌ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์—ˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys

N = int(input())


def solution():
    min_memo = [[-1] * 3 for _ in range(2)]
    max_memo = [[-1] * 3 for _ in range(2)]
    board = list(map(int, sys.stdin.readline().split()))

    for i in range(3):
        min_memo[0][i] = board[i]
        max_memo[0][i] = board[i]

    for x in range(1, N):
        board = list(map(int, sys.stdin.readline().split()))

        min_memo[x % 2][0] = min(min_memo[(x - 1) % 2][0], min_memo[(x - 1) % 2][1]) + board[0]
        min_memo[x % 2][1] = min(min_memo[(x - 1) % 2][0], min_memo[(x - 1) % 2][1], min_memo[(x - 1) % 2][2]) + board[1]
        min_memo[x % 2][2] = min(min_memo[(x - 1) % 2][1], min_memo[(x - 1) % 2][2]) + board[2]

        max_memo[x % 2][0] = max(max_memo[(x - 1) % 2][0], max_memo[(x - 1) % 2][1]) + board[0]
        max_memo[x % 2][1] = max(max_memo[(x - 1) % 2][0], max_memo[(x - 1) % 2][1], max_memo[(x - 1) % 2][2]) + board[1]
        max_memo[x % 2][2] = max(max_memo[(x - 1) % 2][1], max_memo[(x - 1) % 2][2]) + board[2]

    max_value = max(max_memo[(N - 1) % 2])
    min_value = min(min_memo[(N - 1) % 2])

    return f"{max_value} {min_value}"


print(solution())
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€