ν‹°μŠ€ν† λ¦¬ λ·°

728x90
λ°˜μ‘ν˜•

문제

 

17485번: μ§„μš°μ˜ 달 μ—¬ν–‰ (Large)

첫쀄에 지ꡬ와 달 사이 곡간을 λ‚˜νƒ€λ‚΄λŠ” ν–‰λ ¬μ˜ 크기λ₯Ό λ‚˜νƒ€λ‚΄λŠ” N, M (2 ≤ N, M ≤ 1000)이 주어진닀. λ‹€μŒ N쀄 λ™μ•ˆ 각 ν–‰λ ¬μ˜ μ›μ†Œ 값이 주어진닀. 각 ν–‰λ ¬μ˜ μ›μ†Œκ°’μ€ 100 μ΄ν•˜μ˜ μžμ—°μˆ˜μ΄λ‹€.

www.acmicpc.net

 

문제 풀이

 μ™„μ „ 탐색 + 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
λ°˜μ‘ν˜•
λŒ“κΈ€
κΈ€ 보관함
μ΅œκ·Όμ— 올라온 κΈ€
μ΅œκ·Όμ— 달린 λŒ“κΈ€