F - Three Paths on a Tree CodeForces - 1294F

F - Three Paths on a Tree CodeForces - 1294F

You are given an unweighted tree with nn vertices. Recall that a tree is a connected undirected graph without cycles.

Your task is to choose three distinct vertices a,b,ca,b,c on this tree such that the number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc is the maximum possible. See the notes section for a better understanding.

The simple path is the path that visits each vertex at most once.

Input
The first line contains one integer number n (3≤n≤2⋅1053≤n≤2⋅105) — the number of vertices in the tree.

Next n− lines describe the edges of the tree in form ai,biai,bi (1≤ai1≤ai, bi≤nbi≤n, ai≠biai≠bi). It is guaranteed that given graph is a tree.

Output
In the first line print one integer resres — the maximum number of edges which belong to at least one of the simple paths between aa and bb, bb and cc, or aa and cc.

In the second line print three integers a,b,ca,b,c such that 1≤a,b,c≤n1≤a,b,c≤n and a≠,b≠c,a≠c

If there are several answers, you can print any.

Example
inputCopy
8
1 2
2 3
3 4
4 5
4 6
3 7
3 8
outputCopy
5
1 8 6
Note
The picture corresponding to the first example (and another one correct answer):

F - Three Paths on a Tree CodeForces - 1294F

If you choose vertices 1,5,61,5,6 then the path between 11 and 55 consists of edges (1,2),(2,3),(3,4),(4,5)(1,2),(2,3),(3,4),(4,5), the path between 11 and 66 consists of edges (1,2),(2,3),(3,4),(4,6)(1,2),(2,3),(3,4),(4,6) and the path between 55 and 66 consists of edges (4,5),(4,6)(4,5),(4,6). The union of these paths is (1,2),(2,3),(3,4),(4,5),(4,6)(1,2),(2,3),(3,4),(4,5),(4,6) so the answer is 55. It can be shown that there is no better answer.

题意

输入n(3≤n≤2⋅105) ,表示有n个点,接下来有n-1条边,构成一个树形结构;
让你找到 a,b,c三个点, a≠b,b≠c,a≠c,设 a 到 b 的距离为dis(a,b)
使得dis(a,b)+dis(b,c)+dis(a,c)的值最大;
输出连接a,b,c三个点的边的个数,然后输出a,b,c;
对于一棵树来说,最长的路,就是树的直径;

题解:

方法一。

先找树的直径

树的直径两点的确定方法:

先取树上随意一点x;
一次dfs求出x能到达的最远点 便是树的直径的一端点a;
再来一次dfs求出a能到达的最远点 便是树的直径的另一端点b;

对于这道题,bfs找到一个端点到(树的直径最远,也就是到a到b这条路径最远)
那么这个点就是c点;

方法二:树形dp,我还不会