結果

問題 No.277 根掘り葉掘り
ユーザー nebukuro09nebukuro09
提出日時 2016-10-03 16:16:09
言語 Python2
(2.7.18)
結果
AC  
実行時間 746 ms / 3,000 ms
コード長 1,095 bytes
コンパイル時間 175 ms
コンパイル使用メモリ 6,948 KB
実行使用メモリ 36,948 KB
最終ジャッジ日時 2024-05-01 11:20:49
合計ジャッジ時間 8,808 ms
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 14 ms
6,816 KB
testcase_01 AC 14 ms
6,940 KB
testcase_02 AC 13 ms
6,944 KB
testcase_03 AC 15 ms
6,940 KB
testcase_04 AC 14 ms
6,944 KB
testcase_05 AC 14 ms
6,940 KB
testcase_06 AC 14 ms
6,944 KB
testcase_07 AC 14 ms
6,944 KB
testcase_08 AC 14 ms
6,940 KB
testcase_09 AC 662 ms
31,360 KB
testcase_10 AC 654 ms
36,948 KB
testcase_11 AC 687 ms
34,144 KB
testcase_12 AC 692 ms
33,752 KB
testcase_13 AC 746 ms
34,860 KB
testcase_14 AC 695 ms
35,748 KB
testcase_15 AC 687 ms
33,852 KB
testcase_16 AC 716 ms
33,996 KB
testcase_17 AC 668 ms
34,264 KB
testcase_18 AC 666 ms
33,960 KB
testcase_19 AC 667 ms
33,976 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