树的直径

两次\(DFS\)

\(O(n)\)

第一次随机从一个点出发,寻找距离当前点,最远的一个叶子节点,命名为\(pos\)

然后从 \(pos\) 出发,寻找距离\(pos\) 最远的一个叶子节点,这段距离就是树的直径

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int e[N*2],ne[N*2],w[N*2],idx,pos,d[N],h[N],ans;
void add(int a,int b,int c) {
    e[idx] = b;
    w[idx] = c;
    ne[idx] = h[a];
    h[a] = idx ++;
}
void dfs(int u,int fa) {
    if(d[u] > ans) ans = d[u],pos = u;
    for(int i = h[u]; ~i;i = ne[i]) {
        int j = e[i];
        if(j == fa) continue;// 因为是无向边存储,会遍历到父亲节点,去掉即可
        d[j] = d[u] + w[i];// w[i] 代表 fa-> j 的边权 ,d[j] 就是 节点 j 的深度
        dfs(j,u);
    }
}
void find(int x) {
    ans = 0;
    d[x] = 0;
    dfs(x,0);
}
int main() {
    int n;
    memset(h,-1,sizeof h);
    cin >> n;
    for(int i = 0;i < n - 1; ++i) {
        int a,b;
        cin >> a >> b;
        add(a,b,1);
        add(b,a,1);
    }
    find(1);// 第一次寻找直径的端点
    find(pos);// 第二次寻找直径的另一端
    cout << ans;
    return 0;
}

模板题
SP1437 PT07Z - Longest path in a tree

原文链接: https://www.cnblogs.com/lukelmouse/p/13160672.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    树的直径

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/356736

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午11:22
下一篇 2023年3月2日 上午11:23

相关推荐