当前位置:网站首页>ACM入门之【树的直径】
ACM入门之【树的直径】
2022-04-21 07:42:00 【辉小歌】
树的直径: 就是树中最长的一条链。
求树的直径一般有两种方法。
方法一:先随便找个点,dfs一下找到最远的一个点,再用找到的点dfs一下,最远的距离就是直径。方法二:随便找个点dfs一下,存一下最远路和次短路。最短路+次短路+1就是直径。
看一下例题:

https://ac.nowcoder.com/acm/contest/136/C
方法一:
#include<bits/stdc++.h>
using namespace std;
const int N=1e6*2+10;
int h[N],e[N],ne[N],idx,n;
int dist[N];
void add(int a,int b)
{
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
void dfs(int u,int fa,int d)
{
dist[u]=d;
for(int i=h[u];i!=-1;i=ne[i])
{
int j=e[i];
if(j==fa) continue;
dfs(j,u,d+1);
}
}
int main(void)
{
cin>>n;
memset(h,-1,sizeof h);
for(int i=1;i<=n-1;i++)
{
int a,b; scanf("%d%d",&a,&b);
add(a,b),add(b,a);
}
dfs(1,-1,1);
int root=1,len=0;
for(int i=1;i<=n;i++) if(len<dist[i]) len=dist[i],root=i;//找到最远的点
dfs(root,-1,1);//再跑一次。
len=0;
for(int i=1;i<=n;i++) len=max(len,dist[i]);//取最远的就是答案。
cout<<len;
return 0;
}
方法二:
#include<bits/stdc++.h>
using namespace std;
const int N=1e6*2+10;
int h[N],e[N],ne[N],idx,n;
int st[N],ans;
void add(int a,int b)
{
e[idx]=b,ne[idx]=h[a],h[a]=idx++;
}
int dfs(int u)
{
int d1=0,d2=0;//最长路,次长路。
st[u]=1;
for(int i=h[u];i!=-1;i=ne[i])
{
int j=e[i];
if(st[j]) continue;
int t=dfs(j);
if(t>=d1) d2=d1,d1=t;
else if(t>d2) d2=t;
}
ans=max(ans,d2+d1+1);
return d1+1;
}
int main(void)
{
cin>>n;
memset(h,-1,sizeof h);
for(int i=1;i<=n-1;i++)
{
int a,b; cin>>a>>b;
add(a,b),add(b,a);
}
dfs(1);
cout<<ans<<endl;
return 0;
}
版权声明
本文为[辉小歌]所创,转载请带上原文链接,感谢
https://huixiaoge.blog.csdn.net/article/details/124310823
边栏推荐
猜你喜欢
随机推荐
作文以记之 ~ 每日温度
localhost和127.0.0.1有什么区别?(转载)
L2-3 sequence traversal of complete binary tree (25 points)
How did you spend your day in Shenzhen?
Use of antv X6 layout
模块化的概念
第八章 事务
4.20学习记录
【MATLAB】绘制泽尼克多项式
MySQL忘记root密码解决方案
记C#的操蛋字符串转Base64和Base64还原字符串
Redis (14) -- master-slave replication of redis
【Pytorch】torch.bmm()方法使用
Brief introduction of Photoshop PS measuring angle
Brief introduction of 6 screenshots of win10
Vim这么难用,为啥这么多人热衷?
Go编译器源代码:语法分析
阿里云性能测试 PTS 3 月新功能
Swift memory management
Yolov5 model environment construction and Google lab training


![[introduction to C language series (8) (9)] Chapter 8 and 9, pointer and structure](/img/98/33ce4ce21f036ace1b75cdddb4f158.png)






