#C5359. Maximum Network Distance (Tree Diameter)
Maximum Network Distance (Tree Diameter)
Maximum Network Distance (Tree Diameter)
You are given a network of computers connected in a tree structure (i.e., exactly n computers and n-1 cables, with no cycles). Your task is to determine the maximum distance between any two computers in the network, which is equivalent to finding the diameter of the tree.
The diameter is defined as the longest shortest path between any two nodes in the tree. In mathematical terms, if \(d(u,v)\) represents the distance between nodes \(u\) and \(v\), then the diameter is given by:
[ \text{diameter} = \max_{u,v \in V} ; d(u,v) ]
You can solve this problem using two breadth-first searches (BFS). First, pick an arbitrary node and perform a BFS to find the farthest node from it. Then, perform a BFS starting from that farthest node to determine the maximum distance, which is the diameter.
inputFormat
The input is read from standard input. The first line contains an integer \(n\) (\(2 \leq n \leq 10^5\)), representing the number of computers in the network. The following \(n-1\) lines each contain two integers \(u\) and \(v\) (\(1 \leq u,v \leq n\)), indicating that there is a cable connecting computer \(u\) and computer \(v\).
outputFormat
Output a single integer to standard output, representing the maximum distance (diameter) between any two computers in the network.
## sample6
1 2
1 3
2 4
3 5
3 6
4
</p>