結果

問題 No.277 根掘り葉掘り
ユーザー しらっ亭
提出日時 2015-09-05 20:50:14
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
WA  
実行時間 -
コード長 1,003 bytes
コンパイル時間 192 ms
コンパイル使用メモリ 12,672 KB
実行使用メモリ 38,580 KB
最終ジャッジ日時 2024-07-19 03:57:06
合計ジャッジ時間 8,217 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 7 WA * 11
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import defaultdict


def solve():
    N = int(input())

    C = defaultdict(list)
    P = [0] * (N + 1)
    for i in range(N - 1):
        x, y = map(int, input().split())
        C[x].append(y)
        P[y] = x

    R = [0] * (N + 1)
    stack = [(1, 0)]
    while stack:
        v, r = stack.pop()
        R[v] = r
        if C[v]:
            for c in C[v]:
                stack.append((c, r+1))

    L = [float('inf')] * (N + 1)
    s = set()
    for i in range(N + 1):
        if not C[i]:
            L[i] = 0
            s.add(i)

    def upd(x, d):
        if L[x] > d:
            L[x] = d
            return True
        return False

    d = 1
    while s:
        ns = set()
        for i in s:
            if upd(P[i], d):
                ns.add(P[i])
            for j in C[i]:
                if upd(j, d):
                    ns.add(j)
        s = ns
        d += 1

    for i in range(1, N + 1):
        print(min(R[i], L[i]))


if __name__ == '__main__':
    solve()
0