Special Nodes

4.7

3 votes
Binary search algorithm, Hard, Algorithms, Approved, Tree
Problem

You have been given a tree consisting of N nodes. Lets consider two pivot nodes in this tree, A and B such that A and B are not equal. For any node u, lets define PivotDistance(u) to be minimum of shortest path distance of u from A and B. Thus PivotDistance(u) = min(dist(u,A),dist(u,B)) where dist(u,A) is the shortest path distance of u from A and dist(u,B) is the shortest path distance of u from B. Note that if u is equal to A or B, then PivotDistance(u) will be 0.

Now consider PivotDistance(u) for all the nodes u in this tree and define maxPivotDistance to be maximum value of PivotDistance(u) for all the nodes u in the tree.

You don't like the higher value of this quantity maxPivotDistance. So you want to minimise the value of maxPivotDistance by choosing the two pivot nodes A and B optimally. Find two pivot nodes A and B for which the value of maxPivotDistance is minimum.

INPUT:
First line will consists of integer N denoting total number of nodes in tree. Next N1 lines will consists of two integers u and v denoting edge between nodes u and v.

OUTPUT:
First line of output should consists of the minimum value of maxPivotDistance that can be obtained by choosing pivot nodes A and B optimally.
Next line of output should consists of two distinct pivot nodes A and B that gives the minimum possible value of maxPivotDistance. If there are many such possible pairs, print any one of them.

CONSTRAINTS:
2N106
1u,vN

Time Limit: 3
Memory Limit: 256
Source Limit:
Explanation

You can see that we we choose nodes 2 and 3 as pivot nodes, PivotDistance(1)=PivotDistance(4)=PivotDistance(5)=PivotDistance(6)=1 and PivotDistance(2)=PivotDistance(3)=0. maxPivotDistance=1.
The other possible correct pair of pivot nodes is (1,3). You can print any pair (2,3) or (1,3).

Editor Image

?