백준 1167 - 트리의 지름 (파이썬)

Updated:

Answer

import sys

sys.setrecursionlimit(10 ** 9)
input = sys.stdin.readline

V = int(input())

tree = [[] for _ in range(V + 1)]

for _ in range(V):
    tmp = list(map(int, input().split()))

    for j in range(1, len(tmp) - 1, 2):
        tree[tmp[0]].append((tmp[j], tmp[j + 1]))

def dfs(start):
    for next, cost in tree[start]:
        if path[next] == 0:
            path[next] = path[start] + cost
            dfs(next)

path = [0] * (V + 1)
dfs(1)
path[1] = 0

index = 0
tmp = 0

for i in range(V + 1):
    if tmp < path[i]:
        tmp = path[i]
        index = i

path = [0] * (V + 1)
dfs(index)
path[index] = 0

print(max(path))

Categories:

Updated: