結果

問題 No.277 根掘り葉掘り
ユーザー ckawatakckawatak
提出日時 2017-08-30 23:27:37
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
TLE  
実行時間 -
コード長 1,171 bytes
コンパイル時間 82 ms
コンパイル使用メモリ 12,800 KB
実行使用メモリ 51,084 KB
最終ジャッジ日時 2024-04-24 07:23:21
合計ジャッジ時間 7,579 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 33 ms
12,800 KB
testcase_01 AC 35 ms
12,800 KB
testcase_02 AC 35 ms
12,672 KB
testcase_03 AC 34 ms
12,672 KB
testcase_04 AC 66 ms
12,672 KB
testcase_05 AC 51 ms
12,800 KB
testcase_06 AC 53 ms
12,672 KB
testcase_07 AC 54 ms
12,672 KB
testcase_08 AC 36 ms
12,800 KB
testcase_09 AC 1,513 ms
43,264 KB
testcase_10 TLE -
testcase_11 -- -
testcase_12 -- -
testcase_13 -- -
testcase_14 -- -
testcase_15 -- -
testcase_16 -- -
testcase_17 -- -
testcase_18 -- -
testcase_19 -- -
権限があれば一括ダウンロードができます

ソースコード

diff #

import queue

INF = 1e9

class Node:
    def __init__(self, id):
        self.id = id
        self.children = []

N = int(input())

nodes = [None] * (N)

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

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

# find distance from the root
d1 = [INF] * 100010
q = queue.Queue()
q.put((0,-1))
d1[0] = 0
while not q.empty():
    m,n = q.get()
    for c in nodes[m].children:
        if c != n and d1[c] == INF:
            d1[c] = min(d1[c], d1[m] + 1)
            q.put((c,m))
        
# find distance from the leaf
d2 = [INF] * 100010
for i in leaves:
    q = queue.Queue()
    q.put((i,-1))
    d2[i] = 0
    while not q.empty():
        m,n = q.get()
        for c in nodes[m].children:
            if c != n:
                d2[c] = min(d2[c], d2[m]+1)
                q.put((c,m))

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