树的直径定义:我们将一棵树T = ( V,E )的直径定义为maxδ ( u,v ) ( u,v ∈ V ),也就是说,树中所有最短路径距离的最大值即为树的直径。
2次dfs(取任意一点x,找到距x最远的点p,再找到距p的最远距离的点q,dist[p][q],为树的直径)
模板:
#include <bits/stdc++.h>
using namespace std;
const int maxn=1e5+100;
struct node
{
int to,nxt,w;
}e[maxn];
int head[maxn],cnt;
int dis[maxn];
int ans;
int se;
void add(int u,int v,int w)
{
e[cnt].to=v;
e[cnt].w=w;
e[cnt].nxt=head[u];
head[u]=cnt++;
}
void dfs(int x,int fa)
{
if(ans<dis[x])
{
ans=dis[x];
se=x;
}
for(int i=head[x];i!=-1;i=e[i].nxt)
{
int to=e[i].to;
if(to==fa) continue;
dis[to]=dis[x]+e[i].w;
dfs(to,x);
}
}
int main()
{
int n,m;
cin>>n>>m;
int x,y,w;
memset(head,-1,sizeof(head));
for(int i=1;i<=m;i++)
{
cin>>x>>y>>w;
add(x,y,w);
add(y,x,w);
}
ans=0;
dis[1]=0;
dfs(1,0);
ans=0;
dis[se]=0;
dfs(se,0);
cout<<ans<<endl;
return 0;
}