結果

問題 No.277 根掘り葉掘り
ユーザー nebukuro09nebukuro09
提出日時 2016-10-03 16:15:50
言語 PyPy2
(7.3.15)
結果
AC  
実行時間 287 ms / 3,000 ms
コード長 1,095 bytes
コンパイル時間 654 ms
コンパイル使用メモリ 76,840 KB
実行使用メモリ 114,840 KB
最終ジャッジ日時 2024-05-01 11:20:38
合計ジャッジ時間 5,620 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 75 ms
77,472 KB
testcase_01 AC 73 ms
77,684 KB
testcase_02 AC 78 ms
77,840 KB
testcase_03 AC 80 ms
77,468 KB
testcase_04 AC 79 ms
77,480 KB
testcase_05 AC 78 ms
77,372 KB
testcase_06 AC 77 ms
77,976 KB
testcase_07 AC 76 ms
78,000 KB
testcase_08 AC 75 ms
77,740 KB
testcase_09 AC 253 ms
93,992 KB
testcase_10 AC 247 ms
114,840 KB
testcase_11 AC 251 ms
96,672 KB
testcase_12 AC 252 ms
98,436 KB
testcase_13 AC 287 ms
98,576 KB
testcase_14 AC 268 ms
96,696 KB
testcase_15 AC 263 ms
96,532 KB
testcase_16 AC 264 ms
97,344 KB
testcase_17 AC 269 ms
96,440 KB
testcase_18 AC 273 ms
96,576 KB
testcase_19 AC 281 ms
97,320 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

from collections import deque

N = input()
rinsetsu = [[] for _ in xrange(N)]
for i in xrange(N-1):
    x, y = map(int, raw_input().split())
    x -= 1
    y -= 1
    rinsetsu[x].append(y)
    rinsetsu[y].append(x)
ans = [float('inf') for _ in xrange(N)]

def dfs(start):
    stack = [(start, None)]
    leaves = []
    while len(stack) > 0:
        node, parent = stack.pop()
        if len(rinsetsu[node]) == 1 and parent is not None:
            leaves.append(node)
            continue
        for nn in rinsetsu[node]:
            if nn == parent:
                continue
            stack.append((nn, node))
    return leaves

def bfs(starts):
    q = deque()
    for s in starts:
        q.append((s, 0))
    visited = [False for _ in xrange(N)]
    while len(q) > 0:
        node, depth = q.popleft()
        if visited[node]:
            continue
        visited[node] = True
        ans[node] = min(ans[node], depth)
        for nn in rinsetsu[node]:
            if not visited[nn]:
                q.append((nn, depth+1))

leaves = dfs(0) + [0]
bfs(leaves)
for a in ans:
    print a
0