結果

問題 No.277 根掘り葉掘り
ユーザー ckawatakckawatak
提出日時 2017-09-05 22:26:05
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
AC  
実行時間 986 ms / 3,000 ms
コード長 943 bytes
コンパイル時間 85 ms
コンパイル使用メモリ 12,928 KB
実行使用メモリ 37,248 KB
最終ジャッジ日時 2024-04-24 14:08:45
合計ジャッジ時間 12,468 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 27 ms
10,752 KB
testcase_01 AC 27 ms
10,752 KB
testcase_02 AC 28 ms
10,880 KB
testcase_03 AC 28 ms
10,880 KB
testcase_04 AC 28 ms
10,624 KB
testcase_05 AC 29 ms
10,624 KB
testcase_06 AC 30 ms
10,880 KB
testcase_07 AC 29 ms
10,880 KB
testcase_08 AC 27 ms
10,624 KB
testcase_09 AC 858 ms
35,328 KB
testcase_10 AC 800 ms
37,184 KB
testcase_11 AC 901 ms
34,176 KB
testcase_12 AC 909 ms
37,248 KB
testcase_13 AC 943 ms
34,176 KB
testcase_14 AC 876 ms
35,712 KB
testcase_15 AC 875 ms
36,864 KB
testcase_16 AC 977 ms
36,224 KB
testcase_17 AC 986 ms
36,736 KB
testcase_18 AC 938 ms
36,864 KB
testcase_19 AC 904 ms
37,120 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque

INF = float('inf')

N = int(input())

nodes = [[] for _ in range(N)]

for n in range(N-1):
    x,y = list(map(int, input().split(' ')))
    x -= 1
    y -= 1
    nodes[x].append(y)
    nodes[y].append(x)

# find leaves
leaves = []    
for i in range(N):
    if len(nodes[i]) == 1 and i != 0:
        leaves.append(i)

# find distance from the root
d1 = [INF] * N
q = deque()
q.append((0,-1))
d1[0] = 0
while 0 < len(q):
    m,n = q.popleft()
    for c in nodes[m]:
        if c != n and d1[c] == INF:
            d1[c] = min(d1[c], d1[m] + 1)
            q.append((c,m))
        
# find distance from the leaf
d2 = [INF] * N
q = deque()
for i in leaves:
    q.append((i,-1))
    d2[i] = 0
    
while 0 < len(q):
    m,n = q.popleft()
    for c in nodes[m]:
        if c != n and d2[c] == INF:
            d2[c] = min(d2[c], d2[m] + 1)
            q.append((c,m))

for i in range(N):
    print(min(d1[i], d2[i]))
0