#C9231. Longest Path in Tree

    ID: 53302 Type: Default 1000ms 256MiB

Longest Path in Tree

Longest Path in Tree

You are given an undirected and unweighted tree with n vertices. A tree is a connected graph without cycles. Your task is to determine the length of the longest path in the tree, otherwise known as the diameter of the tree.

The input consists of an integer n and n-1 edges where each edge connects two vertices. The longest path is defined as the maximum number of edges between any two vertices in the tree.

One common approach is to perform a breadth-first search (BFS) from an arbitrary node to find the farthest node from it, and then perform another BFS from this farthest node to determine the diameter of the tree.

The formula for the diameter can be stated in terms of distances as:

$$\text{diameter} = \max_{u,v \in V} \, d(u,v)$$

where d(u,v) is the shortest distance between vertices u and v.

inputFormat

The first line contains a single integer n (2 ≤ n ≤ 105), representing the number of vertices in the tree.

The following n-1 lines each contain two space-separated integers u and v (1 ≤ u, v ≤ n), describing an undirected edge of the tree.

You can assume the input forms a valid tree.

outputFormat

Output a single integer, representing the length (i.e., the number of edges) of the longest path (diameter) in the tree.

## sample
5
1 2
1 3
3 4
3 5
3