ν°μ€ν 리 λ·°
π¨π» μ½λ©ν
μ€νΈ/λ°±μ€
λ°±μ€: 17485 μ§μ°μ λ¬ μ¬ν (Large)
dirmathfl 2021. 4. 9. 00:05728x90
λ°μν
λ¬Έμ
λ¬Έμ νμ΄
μμ νμ + dp λ¬Έμ μ΄λ€. νμν κ²½λ‘λ₯Ό λ€μ νμνμ§ μκΈ° μν΄μλ λ©λͺ¨μ΄μ μ΄μ μ ν΅ν΄, κ° κ³΅κ°μ μ§λ λ μ΅μκ°μ κΈ°λ‘νκ³ μ΄μ μ κ°μ μ¬μ©νλ λ°©μμ μ¬μ©νλ©΄ λλ€. μ¬κ·λ‘ νλ©΄ λ¬Έμ λ μ΄λ ΅μ§ μκ² ν μ μμΌλ©° μ νμμ λ€μκ³Ό κ°λ€.
`dp[r][c][cur_dir] = min(dp[r][c][cur_dir], recursive_find(next_r, next_c), next_dir) + board[r][c])`μ΄λ©°, μ΄λ₯Ό ν΅ν΄, μ΅μκ°μ λ°μνμ¬ λΆνμν νμμ λ§μ μ μλ€.
μ½λ
from sys import stdin, maxsize, setrecursionlimit
def visitable(loc, cur_dir, next_dir):
r, c = loc
return cur_dir != next_dir and 0 <= c < M
def solve(loc, cur_dir):
r, c = loc
#
if r == N:
return 0
# μ°Ύμ κ°μ΄ μλ κ²½μ°, νμν νμ μμ
if dp[r][c][cur_dir] != maxsize:
return dp[r][c][cur_dir]
for next_dir, dc in enumerate(dirs):
# rλ νμ 1μ© μ¦κ°, cλ 3λ°©ν₯ (β, ↓, β) μ€ νλλ‘ μ¦κ°
next_r, next_c = r + 1, c + dc
if visitable((next_r, next_c), cur_dir, next_dir):
dp[r][c][cur_dir] = min(dp[r][c][cur_dir], solve((next_r, next_c), next_dir) + board[r][c])
return dp[r][c][cur_dir]
if __name__ == "__main__":
# μ¬μ©νμ§ μμΌλ©΄ (RecursionError) λ°μ
setrecursionlimit(2000)
answer = maxsize
N, M = map(int, stdin.readline().split())
board = [list(map(int, stdin.readline().split())) for _ in range(N)]
dp = [[[maxsize] * 3 for _ in range(M)] for _ in range(N)]
# β, ↓, β
dirs = (-1, 0, 1)
answer = maxsize
for i in range(M):
for j in range(3):
answer = min(answer, solve((0, i), j))
print(answer)
PyPy3λ‘ μ μΆνμ¬μΌ μκ°μ΄κ³Όκ° λ°μλμ§ μμΌλ©°, `setrecursionlimit`μ μ¬μ©νμ§ μμΌλ©΄ λ°νμ μλ¬κ° λ°μνλ€.
728x90
λ°μν
'π¨βπ» μ½λ©ν μ€νΈ > λ°±μ€' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
λ°±μ€: 20055 μ»¨λ² μ΄μ΄ λ²¨νΈ μμ λ‘λ΄ (0) | 2021.04.13 |
---|---|
λ°±μ€: 14567 μ μκ³Όλͺ©(Prerequisite) (0) | 2021.04.13 |
λ°±μ€: 1106 νΈν (0) | 2021.04.07 |
λ°±μ€: 20056 λ§λ²μ¬ μμ΄μ νμ΄μ΄λ³Ό (0) | 2021.04.05 |
λ°±μ€: 17135 μΊμ¬ λνμ€ (0) | 2021.04.04 |
λκΈ
κΈ λ³΄κ΄ν¨
μ΅κ·Όμ μ¬λΌμ¨ κΈ
μ΅κ·Όμ λ¬λ¦° λκΈ