Editorial
Perform a depth-first search starting from any vertex, for example, from vertex . Find the vertex farthest from and denote it as vertex . Then, start a depth-first search from vertex to find the vertex that is farthest from , which we'll denote as vertex . The distance between vertices and will then be the maximum possible and equal to the diameter of the tree.
Example
Consider the tree from the example.
The diameter of the tree is . The maximum distance is achieved, for example, between vertices and .
Exercise
Find the diameter of the tree.
Algorithm implementation
Store the input tree in the adjacency list . Store the shortest distances from the source to each vertex in the array .
vector<vector<int>> g; vector<int> dist;
The dfs function performs a depth-first search from vertex . The shortest distance from the source to vertex is . The parent of vertex in the depth-first search is .
void dfs(int v, int d, int p = -1) {
Store the shortest distance from the source to vertex in .
dist[v] = d;
Iterate over all edges . For each son to of vertex (where is not a parent of ) initiate a depth-first search. The distance from the source to vertex will be .
for (int to : g[v]) if (to != p) dfs(to, d + 1, v); }
The main part of the program. Read the input data.
scanf("%d", &n); g.resize(n + 1); dist.resize(n + 1);
Construct an undirected tree.
for (i = 1; i < n; i++) { scanf("%d %d", &u, &v); g[u].push_back(v); g[v].push_back(u); }
Find the shortest distances from vertex to all other vertices. The vertex farthest from it is .
dfs(1, 0, -1); a = max_element(dist.begin(), dist.begin() + n + 1) – dist.begin();
Find the shortest distances from vertex to all other vertices. The vertex farthest from it is .
dfs(a, 0, -1); b = max_element(dist.begin(), dist.begin() + n + 1) – dist.begin();
Print the diameter of the tree — the shortest distance from to .
printf("%d\n", dist[b]);