結果

問題 No.34 砂漠の行商人
ユーザー rlangevin
提出日時 2023-09-19 12:31:13
言語 PyPy3
(7.3.15)
結果
AC  
実行時間 3,358 ms / 5,000 ms
コード長 1,232 bytes
コンパイル時間 200 ms
コンパイル使用メモリ 82,048 KB
実行使用メモリ 478,844 KB
最終ジャッジ日時 2024-07-05 21:41:28
合計ジャッジ時間 9,065 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 26
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import *
inf = 10 ** 18

N, V, sx, sy, gx, gy = map(int, input().split())
sx, sy, gx, gy = sx-1, sy-1, gx-1, gy-1
d = abs(sx - gx) + abs(sy - gy)
L = []
for i in range(N):
    L.append(list(map(int, input().split())))

if V > d * 9:
    print(d)
    exit()

def f(x, y, v):
    return x + y * N + v * N * N

def g(n):
    v = n // (N * N)
    n %= N * N
    y, x = divmod(n, N)
    return x, y, v 

dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
Q = deque([])
dist = defaultdict(lambda:inf)
val = [[-1] * N for i in range(N)]
s =  f(sy, sx, V)
dist[s] = 0
Q.append(s)
x, y, vv = g(s)
val[sy][sx] = V

while Q:
    u = Q.popleft()
    px, py, vv = g(u)
    for k in range(4):
        x = px + dx[k]
        y = py + dy[k]
        if x < 0 or x > N - 1 or y < 0 or y > N - 1:
            continue
        if vv - L[x][y] <= 0:
            continue
        if val[x][y] > vv:
            continue
        v = f(x, y, vv - L[x][y])
        if v in dist:
            continue
        
        dist[v] = dist[u] + 1
        if x == gy and y == gx:
            print(dist[v])
            exit()
        Q.append(v)

ans = inf
for v in range(1, V + 1):
    ans = min(ans, dist[f(gy, gx, v)])

print(ans) if ans != inf else print(-1)
0