当前位置:网站首页>Introduction to ACM [tree diameter]
Introduction to ACM [tree diameter]
2022-04-21 08:18:00 【Hui Xiaoge】
The diameter of the tree : Is the longest chain in the tree .
There are generally two ways to find the diameter of a tree .
Method 1 :Just find a spot ,dfs Find the farthest point , Then find the point dfs once , The furthest distance is the diameter .Method 2 :Just find a spot dfs once , Save the farthest way and secondary short circuit . shortest path + A short circuit +1 It's the diameter .
Take a look at the example :

https://ac.nowcoder.com/acm/contest/136/C
Method 1 :
#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;// Find the farthest point
dfs(root,-1,1);// Run again .
len=0;
for(int i=1;i<=n;i++) len=max(len,dist[i]);// The furthest is the answer .
cout<<len;
return 0;
}
Method 2 :
#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;// The longest way , Second long road .
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;
}
版权声明
本文为[Hui Xiaoge]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204210742434763.html
边栏推荐
猜你喜欢
随机推荐
求其最大公约数和最小公倍数
Brief introduction of 6 screenshots of win10
Kernel PWN learning (1) -- environment construction
【Pytorch】Tensor.contiguous()使用与理解
Kotlin的扩展函数知识点
目录、文件夹、文件三者的区别
Antv X6 画布平移
An error occurred when VMware prompted to restore the snapshot. The required file could not be found
Ehcart map
二、微信小程序-快速回顾 ( 页面文件 )
实验一:数据库的基本操作
L2-3 完全二叉树的层序遍历 (25 分)
第五章 函数
Echart double line - echart chart (II)
Detailed explanation of Web vulnerability: SQL injection vulnerability
Installation of redis in Linux
redis在linux的安装
[template] optimized drawing of line segment tree
4.20 learning records
File转换成MultiPartFile









