树的直径的定义
一棵树上的最长路径。
树的直径的实现
在树中随便找一个点进行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.
<