* Summary of Others Blogs
The diameter of the tree (Diameter) refers to the longest simple path on the tree.
The method of finding the diameter: two times BFS (or DFS)
Choose a point u as the starting point, a BFS traversal of the tree to find the farthest point from U V
Take V as the starting point, then the BFS traversal to find the farthest point W from v. The path length of V to W is the diameter of the tree
* Simple Proof
So the original problem can be found in O (E) time
The key is to prove the correctness of the first traversal, that is, for any point u, the furthest point from the V must be the longest end.
If u is on the longest path, then v must be the longest end. Can be used contradiction: Assuming that V is not the longest end, then there is another point V ' makes (u→v ') is the longest part, so Len (U→v ') > Len (u→v). But this contradicts the condition that "V is the farthest point from U".
If u is not on the longest path, you must have an intersection of C on the road to its farthest point and the longest path, and (C→V) is coincident with the last half of the longest road (why?), that is, v must be the longest end.
BFS
DFS
An pity Dorado graph, given a point in the figure, the shortest path length as a distance, find out the furthest point, the distance between the two points is called the eccentric distance.
To calculate the radius of an image without a direction, just count the shortest path between two points and then calculate by definition.
Use Floyd to search for the longest path (that is, diameter) first.
1 intd[Ten][Ten];//adjacency Matrix2 intecc[Ten];//the eccentric distance of the dots3 4 voidDiameter_radius ()5 {6 //Floyd-warshall Algorithm7 for(intk=0; k<Ten; ++k)8 for(intI=0; i<Ten; ++i)9 for(intj=0; j<Ten; ++j)TenD[i][j] = min (D[i][j], d[i][k] +d[k][j]); One A //calculate the eccentric distance -memset (ECC,0x7f,sizeof(ECC)); - for(intI=0; i<Ten; ++i) the for(intj=0; j<Ten; ++j) -Ecc[i] =min (ecc[i], d[i][j]); - - //calculate the diameter and the half diameter + intdiameter =0; - intRadius =1e9; + for(intI=0; i<Ten; ++i) A { atdiameter =max (diameter, ecc[i]); -Radius =min (radius, ecc[i]); - } - - /* - //The diameter can also be calculated in for (int i=0; i<10; ++i) - for (int j=0; j<10; ++j) to diameter = max (diameter, d[i][j]); + */ -}Floyd
Each of the paths of a tree must intersect at the same point (the same group of dots).
1. Counter-evidence. Now there are two separate paths, but a tree is connected to each point, so the two open diameter, there must be a connection between each other, once connected, the momentum will become a longer straight path, contradiction between. Therefore all paths must intersect. 2. Counter-evidence. Now there are two paths that intersect at a certain point, and if the other path intersects the two paths at the other, it will become a longer straight path, a contradiction. So all the paths must intersect at the same point (the same group of dots).
The diameter of the tree