树的直径的定义
一棵树上的最长路径。
树的直径的实现
在树中随便找一个点进行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.
题目大意
n个牧场和m条路径构成一棵树,求最远的两牧场的距离。
输入格式
如样例所示,第一行n,m(m当然是n-1)。
接下来m行每行三个数x、y、z和一个字符,表示x牧场、y之间有一条长为z的路径(字符没用,表示东南西北)。
输出格式
输出最远的两牧场间的距离。
样例数据
输入
7 6
1 6 13 E
6 3 9 E
3 5 7 S
4 1 3 N
2 4 20 W
4 7 2 S
输出
52
分析:树的直径模板
代码
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<ctime>
#include<cmath>
#include<algorithm>
#include<cctype>
#include<iomanip>
#include<queue>
#include<set>
using namespace std;
int getint()
{
int sum=0,f=1;
char ch;
for(ch=getchar();!isdigit(ch)&&ch!='-';ch=getchar());
if(ch=='-')
{
f=-1;
ch=getchar();
}
for(;isdigit(ch);ch=getchar())
sum=(sum<<3)+(sum<<1)+ch-48;
return sum*f;
}
const int maxn=50010;
int n,m,x,y,z,tot,maxi,v,ans;
int dis[maxn],first[maxn],nxt[maxn*2],to[maxn*2],w[maxn*2];
void addedge(int x,int y,int z)
{
tot++;
nxt[tot]=first[x];
first[x]=tot;
to[tot]=y;
w[tot]=z;
tot++;
nxt[tot]=first[y];
first[y]=tot;
to[tot]=x;
w[tot]=z;
}
void dfs(int u,int fa)
{
for(int p=first[u];p;p=nxt[p])
{
int v=to[p];
if(v!=fa)
{
if(dis[v]>dis[u]+w[p])
{
dis[v]=dis[u]+w[p];
dfs(v,u);
}
}
}
}
int main()
{
freopen("length.in","r",stdin);
freopen("length.out","w",stdout);
n=getint(),m=getint();
for(int i=1;i<=m;++i)
{
x=getint(),y=getint(),z=getint();
char ch=getchar();
addedge(x,y,z);
}
memset(dis,127,sizeof(dis));
dis[1]=0;//我随便选的点就是1号节点
dfs(1,0);//dfs
for(int i=1;i<=n;++i)
if(dis[i]>maxi)
maxi=dis[i],v=i;//找到距离此点最远的点
memset(dis,127,sizeof(dis));
dis[v]=0;
dfs(v,0);//再次dfs
for(int i=1;i<=n;++i)
if(dis[i]>ans)
ans=dis[i];//得到答案
cout<<ans<<'\n';
return 0;
}
本篇完。