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):

在这里插入图片描述

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,我还不会

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值