結果

問題 No.3679 なんかでっかい虫リターンズ
コンテスト
ユーザー Kato, H.
提出日時 2026-09-05 15:13:40
言語 PyPy3
(7.3.23)
コンパイル:
pypy3 -mpy_compile _filename_
実行:
pypy3 _filename_
結果
AC  
実行時間 181 ms / 2,000 ms
+ 252µs
コード長 2,083 bytes
記録
記録タグの例:
初AC ショートコード 純ショートコード 純主流ショートコード 最速実行時間
コンパイル時間 218 ms
コンパイル使用メモリ 95,824 KB
実行使用メモリ 97,688 KB
最終ジャッジ日時 2026-09-05 15:13:53
合計ジャッジ時間 5,511 ms
ジャッジサーバーID
(参考情報)
judge1_0 / judge2_0
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 17
権限があれば一括ダウンロードができます

ソースコード

diff #
raw source code

# -*- coding: utf-8 -*-


def main():
    import sys
    from collections import deque
    from typing import Any, List, Tuple

    input = sys.stdin.readline

    h, w = map(int, input().split())
    a, b = map(int, input().split())
    r1, c1, r2, c2 = map(int, input().split())
    p, q = map(int, input().split())
    a -= 1
    b -= 1
    r1 -= 1
    c1 -= 1
    r2 -= 1
    c2 -= 1
    p -= 1
    q -= 1
    # TODO: Change input format if needs.
    grid = [[None] * w for _ in range(h)]

    def bfs_for_grid(
        grid: list[list[Any]], h: int, w: int, sy: int = 0, sx: int = 0
    ) -> tuple[list[list[bool]], list[list[int]]]:
        d = deque()
        d.append((sy, sx))
        visited = [[False] * w for _ in range(h)]
        pending = -1
        dist = [[pending] * w for _ in range(h)]
        dist[sy][sx] = 0  # Initialize
        dxy = [(-1, 0), (1, 0), (0, -1), (0, 1)]

        while d:
            y, x = d.popleft()

            if dist[y][x] == pending:
                continue
            if visited[y][x]:
                continue

            visited[y][x] = True

            for dx, dy in dxy:
                nx = x + dx
                ny = y + dy

                if nx < 0 or nx >= w or ny < 0 or ny >= h:
                    continue
                if visited[ny][nx]:
                    continue
                if dist[ny][nx] != pending and dist[ny][nx] <= dist[y][x]:
                    continue

                dist[ny][nx] = dist[y][x] + 1  # Update ans
                d.append((ny, nx))

        return visited, dist

    _, dist1 = bfs_for_grid(grid=grid, h=h, w=w, sy=a, sx=b)
    _, dist2 = bfs_for_grid(grid=grid, h=h, w=w, sy=p, sx=q)
    inf = 10**18
    ans = inf

    for i in range(h):
        for j in range(w):
            candidate = 0

            if not (r1 <= i <= r2):
                continue
            if not (c1 <= j <= c2):
                continue

            candidate += dist1[i][j] + dist2[i][j] + dist2[a][b]
            ans = min(ans, candidate)

    print(ans)


if __name__ == "__main__":
    main()
0