結果

問題 No.340 雪の足跡
ユーザー gew1fw
提出日時 2025-06-12 21:01:36
言語 PyPy3
(7.3.15)
結果
TLE  
実行時間 -
コード長 1,990 bytes
コンパイル時間 183 ms
コンパイル使用メモリ 82,412 KB
実行使用メモリ 110,444 KB
最終ジャッジ日時 2025-06-12 21:04:25
合計ジャッジ時間 7,812 ms
ジャッジサーバーID
(参考情報)
judge3 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 5
other AC * 12 TLE * 4 -- * 16
権限があれば一括ダウンロードができます

ソースコード

diff #

import sys
from collections import deque, defaultdict

def process_segment(a, b, W, graph):
    wa, ha = a % W, a // W
    wb, hb = b % W, b // W

    if wa == wb:
        step = 1 if hb > ha else -1
        current_h = ha
        while current_h != hb:
            next_h = current_h + step
            current = wa + current_h * W
            next_p = wa + next_h * W
            if next_p not in graph[current]:
                graph[current].add(next_p)
            if current not in graph[next_p]:
                graph[next_p].add(current)
            current_h = next_h
    elif ha == hb:
        step = 1 if wb > wa else -1
        current_w = wa
        while current_w != wb:
            next_w = current_w + step
            current = current_w + ha * W
            next_p = next_w + ha * W
            if next_p not in graph[current]:
                graph[current].add(next_p)
            if current not in graph[next_p]:
                graph[next_p].add(current)
            current_w = next_w

def main():
    input = sys.stdin.read().split()
    ptr = 0
    W = int(input[ptr]); ptr +=1
    H = int(input[ptr]); ptr +=1
    N = int(input[ptr]); ptr +=1

    graph = defaultdict(set)

    for _ in range(N):
        M_i = int(input[ptr]); ptr +=1
        path = list(map(int, input[ptr:ptr+M_i+1]))
        ptr += M_i+1
        for j in range(M_i):
            a = path[j]
            b = path[j+1]
            process_segment(a, b, W, graph)

    start = 0
    end = W * H -1

    if start == end:
        print(0)
        return

    distance = [-1] * (W * H)
    distance[start] = 0
    q = deque()
    q.append(start)

    while q:
        u = q.popleft()
        if u == end:
            break
        for v in graph[u]:
            if distance[v] == -1:
                distance[v] = distance[u] + 1
                q.append(v)

    if distance[end] == -1:
        print("Odekakedekinai..")
    else:
        print(distance[end])

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