|
| 1 | +import heapq |
| 2 | +import math |
| 3 | +import sys |
| 4 | + |
| 5 | +from collections import defaultdict |
| 6 | + |
| 7 | +read = lambda: sys.stdin.readline().rstrip() |
| 8 | + |
| 9 | + |
| 10 | +class Problem: |
| 11 | + def __init__(self): |
| 12 | + self.n = int(read()) |
| 13 | + |
| 14 | + self.graph = defaultdict(list) |
| 15 | + for src, dest, distance in [map(int, read().split()) for _ in range(self.n - 1)]: |
| 16 | + self.graph[src].append((dest, distance)) |
| 17 | + self.graph[dest].append((src, distance)) |
| 18 | + |
| 19 | + def solve(self) -> None: |
| 20 | + if self.n == 1: |
| 21 | + print(0) |
| 22 | + return |
| 23 | + |
| 24 | + distances, target = self.dijkstra(1), (0, 0) |
| 25 | + for idx, distance in enumerate(distances): |
| 26 | + if distance > target[0]: |
| 27 | + target = (distance, idx + 1) |
| 28 | + |
| 29 | + print(max(self.dijkstra(target[1]))) |
| 30 | + |
| 31 | + def dijkstra(self, start_vertex: int) -> list[int]: |
| 32 | + queue, distances = [(0, start_vertex)], [0 if idx == start_vertex else math.inf for idx in range(self.n + 1)] |
| 33 | + |
| 34 | + while queue: |
| 35 | + current_distance, current_vertex = heapq.heappop(queue) |
| 36 | + if current_distance > distances[current_vertex]: |
| 37 | + continue |
| 38 | + |
| 39 | + for next_vertex, distance in self.graph[current_vertex]: |
| 40 | + next_distance = current_distance + distance |
| 41 | + if next_distance < distances[next_vertex]: |
| 42 | + distances[next_vertex] = next_distance |
| 43 | + heapq.heappush(queue, (next_distance, next_vertex)) |
| 44 | + |
| 45 | + return list(map(int, distances[1:])) |
| 46 | + |
| 47 | + |
| 48 | +if __name__ == "__main__": |
| 49 | + Problem().solve() |
0 commit comments