I came up with this solution:
1) Select an arbitrary node as the root of r, form a tree. For each subtree in this tree, calculate the number of nodes in the subtree (sheets - single - node -trees).
As an example for this tree
1 / | \ 2 3 4 / \ \ 5 6 7 / \ 8 9
the result will be
9 / | \ 5 1 2 / \ \ 1 3 1 / \ 1 1
2) Calculate the sum of the distances for this selected root. For example, if you select vertex 1 as the root, the sum of the distances is 0 + 1 + 1 + 1 + 2 + 2 + 2 + 3 + 3 = 15
3) Turn the tree to the search depth method . For example, starting from vertex 1, we go to vertex 4. Note that for 7 nodes (1,2,3,5,6,8,9) we get further by 1 (add 7 = 9-2 to the estimate), for the other 2 (4.7), we approach 1 (subtract 2). This gives the sum of the distances equal to 15+ (9-2) -2 = 20.
Suppose we go further from 4 to 7. Now we get the sum of the distances equal to 20+ (9-1) -1 = 27 (then following from 8 vertices and approaching 1 vertex).
As another example, if we go from 1 to 2, we get the sum of the distances equal to 15+ (9-5) -5 = 14. Vertex 2 is actually the solution for this example.
This will be my algorithm.
source share