Tree Diameter#11428

Tree Diameter (Shpjegimi i zgjidhjes)

The diameter of a tree is the length of the longest path in the tree. In other words, we need to find two vertices and such that the distance between them is maximal.

To solve this problem, let’s use the following algorithm:

Then, the distance between vertices and is the maximum among all pairs of vertices in the tree and, therefore, equals 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].

  dist[v] = d;

Iterate over all edges (v, to). 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 d + 1.

  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]);