树的直径(模板)

树的直径定义:我们将一棵树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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值