結果

問題 No.277 根掘り葉掘り
ユーザー H3PO4H3PO4
提出日時 2020-06-09 09:03:27
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 726 ms / 3,000 ms
コード長 884 bytes
コンパイル時間 277 ms
コンパイル使用メモリ 10,832 KB
実行使用メモリ 34,180 KB
最終ジャッジ日時 2023-08-29 01:17:51
合計ジャッジ時間 9,904 ms
ジャッジサーバーID
(参考情報)
judge13 / judge12
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 19 ms
8,640 KB
testcase_01 AC 19 ms
8,704 KB
testcase_02 AC 19 ms
8,552 KB
testcase_03 AC 19 ms
8,552 KB
testcase_04 AC 19 ms
8,652 KB
testcase_05 AC 20 ms
8,660 KB
testcase_06 AC 19 ms
8,592 KB
testcase_07 AC 20 ms
8,668 KB
testcase_08 AC 18 ms
8,732 KB
testcase_09 AC 726 ms
33,112 KB
testcase_10 AC 586 ms
32,680 KB
testcase_11 AC 671 ms
30,648 KB
testcase_12 AC 684 ms
33,808 KB
testcase_13 AC 708 ms
30,932 KB
testcase_14 AC 675 ms
31,812 KB
testcase_15 AC 706 ms
34,180 KB
testcase_16 AC 679 ms
33,504 KB
testcase_17 AC 697 ms
33,756 KB
testcase_18 AC 695 ms
33,848 KB
testcase_19 AC 687 ms
34,096 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque

N = int(input())
int1 = lambda x: int(x) - 1
T = [[] for _ in range(N)]
for _ in range(N - 1):
    a, b = map(int1, input().split())
    T[a].append(b)
    T[b].append(a)

# 根からの距離(dfs)
d = deque([0])
root_distance = [None] * N
root_distance[0] = 0
while d:
    v = d.pop()
    for x in T[v]:
        if root_distance[x] is None:
            root_distance[x] = root_distance[v] + 1
            d.append(x)
# print(root_distance)

# 葉からの距離(bfs)
leaves = {i for i in range(N) if len(T[i]) == 1}
leaf_distance = [0 if i in leaves else None for i in range(N)]
d = deque(leaves)
while d:
    v = d.popleft()
    for x in T[v]:
        if leaf_distance[x] is None:
            leaf_distance[x] = leaf_distance[v] + 1
            d.append(x)
# print(leaf_distance)

for i in range(N):
    print(min(root_distance[i], leaf_distance[i]))
0