-
1967번: 트리의 지름
파일의 첫 번째 줄은 노드의 개수 n(1 ≤ n ≤ 10,000)이다. 둘째 줄부터 n-1개의 줄에 각 간선에 대한 정보가 들어온다. 간선에 대한 정보는 세 개의 정수로 이루어져 있다. 첫 번째 정수는 간선이 연
www.acmicpc.net
코드
import heapq import sys n = int(input()) li = [[] for _ in range(n+1)] for _ in range(n-1): a, b, weight = map(int, input().split(" ")) li[a].append([b,weight]) li[b].append([a,weight]) INF = sys.maxsize def dikstra(start): destination = [INF] * (n+1) destination[start] = 0 heap = [] heapq.heappush(heap, [destination[start], start]) while heap: weight, node = heapq.heappop(heap) for next_node, next_weight in li[node]: new_weight = weight + next_weight if new_weight < destination[next_node]: destination[next_node] = new_weight heapq.heappush(heap, [new_weight, next_node]) return destination destination = dikstra(1) print(max(dikstra(destination.index(max(destination[1:])))[1:]))
'알고리즘 > 백준' 카테고리의 다른 글
[백준] 2263번 트리의 순회 (파이썬) (0) 2022.01.05 [백준] 1991번 트리 순회 (파이썬) (0) 2022.01.05 [백준] 1167번 트리의 지름 (파이썬) (0) 2022.01.05 [백준] 11725번 트리의 부모 찾기 (파이썬) (0) 2022.01.05 [백준] 3273번 두 수의 합 (파이썬) (0) 2022.01.05