#K2651. Finding the Tree Diameter
Finding the Tree Diameter
Finding the Tree Diameter
You are given a tree with (n) nodes and (n-1) edges. Each edge is described by three integers (u), (v), and (w), indicating an undirected edge between nodes (u) and (v) with weight (w). The task is to determine the tree's diameter. The diameter of a tree is defined as (D=\max_{u,v} d(u,v)), where (d(u,v)) is the sum of the weights along the unique path between nodes (u) and (v).
A common approach to solving this problem is to perform a breadth-first search (BFS) starting from an arbitrary node to find the farthest node (u). Then, perform another BFS from (u) to determine the farthest distance from (u), which is the diameter of the tree. This problem challenges you to implement such a solution.
inputFormat
The input is read from standard input (stdin) and has the following format:
- The first line contains a single integer (n) ((2 \le n \le 10^5)) representing the number of nodes in the tree.
- Each of the next (n-1) lines contains three space-separated integers (u), (v), and (w) ((1 \le u,v \le n, 1 \le w \le 10^6)) which represent an edge between nodes (u) and (v) with weight (w).
outputFormat
Output a single integer to standard output (stdout) — the diameter of the tree, which is the maximum sum of weights along the path between any two nodes.## sample
5
1 2 3
1 3 2
2 4 4
2 5 1
9