結果

問題 No.806 木を道に
ユーザー はむ吉🐹はむ吉🐹
提出日時 2019-03-22 22:06:09
言語 Python3
(3.12.2 + numpy 1.26.4 + scipy 1.12.0)
結果
WA  
実行時間 -
コード長 1,241 bytes
コンパイル時間 178 ms
コンパイル使用メモリ 12,100 KB
実行使用メモリ 49,620 KB
最終ジャッジ日時 2023-10-19 09:15:08
合計ジャッジ時間 7,957 ms
ジャッジサーバーID
(参考情報)
judge12 / judge14
このコードへのチャレンジ
(要ログイン)

テストケース

テストケース表示
入力 結果 実行時間
実行使用メモリ
testcase_00 AC 31 ms
10,176 KB
testcase_01 AC 29 ms
10,176 KB
testcase_02 WA -
testcase_03 WA -
testcase_04 AC 31 ms
10,176 KB
testcase_05 WA -
testcase_06 WA -
testcase_07 AC 31 ms
10,176 KB
testcase_08 AC 31 ms
10,176 KB
testcase_09 AC 31 ms
10,176 KB
testcase_10 WA -
testcase_11 WA -
testcase_12 WA -
testcase_13 WA -
testcase_14 WA -
testcase_15 WA -
testcase_16 WA -
testcase_17 WA -
testcase_18 WA -
testcase_19 WA -
testcase_20 WA -
testcase_21 WA -
testcase_22 WA -
testcase_23 WA -
testcase_24 AC 253 ms
31,344 KB
testcase_25 AC 369 ms
42,188 KB
testcase_26 AC 147 ms
22,272 KB
testcase_27 AC 430 ms
47,324 KB
testcase_28 AC 40 ms
11,100 KB
権限があれば一括ダウンロードができます

ソースコード

diff #

import collections


INF = 10 ** 8


def breadth_first_search(adj_list, start_v):
    n = len(adj_list)
    visited = [False] * n
    pred = [None] * n
    dist = [INF] * n
    q = collections.deque()
    q.append(start_v)
    visited[start_v] = True
    dist[start_v] = 0
    while q:
        u = q.popleft()
        for v in adj_list[u]:
            if not visited[v]:
                visited[v] = True
                pred[v] = u
                dist[v] = dist[u] + 1
                q.append(v)
    return pred, dist


def solve(adj_list):
    n = len(adj_list)
    s = 0
    _, dist_a = breadth_first_search(adj_list, s)
    u = max(range(n), key=lambda x: dist_a[x])
    pred, dist_b = breadth_first_search(adj_list, u)
    v = max(range(n), key=lambda x: dist_b[x])
    path = [v]
    while path[-1] != u:
        path.append(pred[path[-1]])
    res = 0
    for w in path:
        if w != v and w != u:
            res += len(adj_list[w]) - 2
    return res


def main():
    n = int(input())
    adj_list = [set() for _ in range(n)]
    for _ in range(n - 1):
        a, b = (int(z) - 1 for z in input().split())
        adj_list[a].add(b)
        adj_list[b].add(a)
    print(solve(adj_list))


if __name__ == "__main__":
    main()
0