#K8576. Tree Diameter
Tree Diameter
Tree Diameter
You are given an undirected tree with n nodes (numbered from 1 to n) and n-1 edges. A tree is a connected acyclic graph. The diameter of a tree is defined as the longest simple path between any two nodes. In other words, if we denote by \(d(u,v)\) the distance (number of edges) between nodes \(u\) and \(v\), then the diameter is given by:
[ \text{diameter} = \max_{1 \le u,v \le n} d(u,v)]
Your task is to compute the diameter of the tree and output three integers: the length of the diameter as well as the two endpoints of the path that defines the diameter. If there are multiple valid answers, any one of them is acceptable.
Note: The input guarantees that the given graph is a tree. Use the standard input and output for reading input data and printing the result.
inputFormat
The first line contains an integer n (\(n \ge 2\)), the number of nodes in the tree.
The next n - 1 lines each contain two integers u and v (1-based indices), representing an edge between nodes u and v.
Input is provided via standard input (stdin).
outputFormat
Output a single line with three integers separated by spaces: the diameter of the tree (i.e. the maximum distance between any two nodes) followed by the two nodes that are the endpoints of this diameter. Output is produced via standard output (stdout).
## sample5
1 2
1 3
3 4
3 5
3 4 2