[学习][poj1985]树的直径 Cow Marathon

博客介绍了树的直径定义,即树上最长路径,并提供了求解树的直径的一种方法:从任意点出发进行两次DFS找到最远点。通过证明保证了这种方法的正确性。接着,给出了POJ1985题目的背景、描述和样例,该题目要求在由n个牧场和m条路径构成的树中寻找最远的两个牧场之间的距离。博客给出了输入输出格式和样例数据,并简单提及了这是一个树的直径问题。
摘要由CSDN通过智能技术生成

树的直径的定义
一棵树上的最长路径。

树的直径的实现
在树中随便找一个点进行dfs,再对找出的距离此点最远的点进行dfs,此时的最远距离就是树的直径。
证明如下:
如图,若s——>t是树的直径,我们在树中随便找一点u,并找距此点最远的点v,若v不是s也不是t,说明u到v的距离大于u到s和u到t的距离,即s到u再到v的距离大于s到t的距离,故树的直径不是s——>t,矛盾。
即u能找到的最远点一定是s、t之一。
这里写图片描述

例题
题目背景
poj1985

题目描述
After hearing about the epidemic of obesity in the USA, Farmer John wants his cows to get more exercise, so he has committed to create a bovine marathon for his cows to run. The marathon route will include a pair of farms and a path comprised of a sequence of roads between them. Since FJ wants the cows to get as much exercise as possible he wants to find the two farms on his map that are the farthest apart from each other (distance being measured in terms of total length of road on the path between the two farms). Help him determine the distances between this farthest pair of farms.

<

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值