結果

問題 No.277 根掘り葉掘り
ユーザー ckawatak
提出日時 2017-08-30 23:27:37
言語 Python3
(3.13.1 + numpy 2.2.1 + scipy 1.14.1)
結果
TLE  
実行時間 -
コード長 1,171 bytes
コンパイル時間 155 ms
コンパイル使用メモリ 12,800 KB
実行使用メモリ 52,688 KB
最終ジャッジ日時 2024-11-06 14:38:05
合計ジャッジ時間 8,004 ms
ジャッジサーバーID
(参考情報)
judge2 / judge5
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 8 TLE * 1 -- * 9
権限があれば一括ダウンロードができます

ソースコード

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