✔ 풀이를 위한 아이디어
✔ 수정 전 코드 [틀렸습니다]
import sys
N = int(sys.stdin.readline())
price = [-1]
dp = [-1, -1]
for _ in range(N):
price.append(list(map(int, sys.stdin.readline().split())))
r = min(price[1][1]+price[2][0], price[1][2]+price[2][0])
g = min(price[1][0]+price[2][1], price[1][2]+price[2][1])
b = min(price[1][0]+price[2][2], price[1][1]+price[2][2])
tmp = min(r, g, b)
if tmp == r:
dp.append((tmp, 0))
elif tmp == g:
dp.append((tmp, 1))
else:
dp.append((tmp, 2))
for i in range(3, N+1):
if dp[i-1][1] == 0:
g = dp[i-1][0]+price[i][1]
b = dp[i-1][0]+price[i][2]
tmp = min(g, b)
if tmp == g:
dp.append((tmp, 1))
else:
dp.append((tmp, 2))
elif dp[i-1][1] == 1:
r = dp[i-1][0]+price[i][0]
b = dp[i-1][0]+price[i][2]
tmp = min(r, b)
if tmp == r:
dp.append((tmp, 0))
else:
dp.append((tmp, 2))
else:
r = dp[i-1][0]+price[i][0]
g = dp[i-1][0]+price[i][1]
tmp = min(r, g)
if tmp == r:
dp.append((tmp, 0))
else:
dp.append((tmp, 1))
print(dp[N][0])
✔ 수정 후 코드
import sys
N = int(sys.stdin.readline())
price = [-1]
dp = [-1]
for _ in range(N):
price.append(list(map(int, sys.stdin.readline().split())))
dp.append((price[1][0], price[1][1], price[1][2]))
for i in range(2, N+1):
r = min(dp[i-1][1]+price[i][0], dp[i-1][2]+price[i][0])
g = min(dp[i-1][0]+price[i][1], dp[i-1][2]+price[i][1])
b = min(dp[i-1][0]+price[i][2], dp[i-1][1]+price[i][2])
dp.append((r, g, b))
print(min(dp[N][0], dp[N][1], dp[N][2]))
✔ 관련 개념