結果

問題 No.277 根掘り葉掘り
ユーザー ckawatakckawatak
提出日時 2017-09-05 00:26:11
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
TLE  
実行時間 -
コード長 947 bytes
コンパイル時間 114 ms
コンパイル使用メモリ 12,928 KB
実行使用メモリ 42,824 KB
最終ジャッジ日時 2024-04-24 12:51:24
合計ジャッジ時間 6,759 ms
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 32 ms
10,880 KB
testcase_01 AC 30 ms
10,880 KB
testcase_02 AC 32 ms
10,752 KB
testcase_03 AC 32 ms
10,880 KB
testcase_04 AC 41 ms
10,752 KB
testcase_05 AC 35 ms
10,880 KB
testcase_06 AC 36 ms
10,880 KB
testcase_07 AC 36 ms
10,880 KB
testcase_08 AC 31 ms
10,880 KB
testcase_09 AC 933 ms
35,200 KB
testcase_10 TLE -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
権限があれば一括ダウンロードができます

ソースコード

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
for i in leaves:
    q = deque()
    q.append((i,-1))
    d2[i] = 0
    while 0 < len(q):
        m,n = q.popleft()
        for c in nodes[m]:
            if c != n:
                d2[c] = min(d2[c], d2[m]+1)
                q.append((c,m))

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