zcmu1369: Graph Theory(求树的直径)

题目链接:https://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=1369

题目大意

给你一棵有N个结点的树,请找出这棵树上相距最远两点的距离(树的直径)。树上结点编号从0-(N-1)。所有相邻结点间的距离都为1。

思路

首先随便取个点为根节点建树跑dfs,我取了0,然后取深度最深的那个节点t,然后再以t为根建树跑dfs,最大深度就是树的直径了。

ac代码

#include<bits/stdc++.h>
using namespace std;
#define ll long long
vector<int> v[105];
int ans, mx;
void dfs(int s, int fa, int dep){
    if(dep > ans){
        ans = dep;
        mx = s;
    }
    for(int i = 0; i < v[s].size(); i ++){
        int t = v[s][i];
        if(t == fa) continue;
        dfs(t, s, dep + 1);
    }
}
int main(){
    int n;
    while(~scanf("%d", &n)){
        for(int i = 0; i < n; i ++) v[i].clear();
        for(int i = 1; i < n; i ++){
            int x, y;
            scanf("%d%d", &x, &y);
            v[x].push_back(y);
            v[y].push_back(x);
        }
        ans = 0, mx = 0;
        dfs(0, -1, 0);
        ans = 0;
        dfs(mx, -1, 0);
        printf("%d\n", ans);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43911947/article/details/113404667
今日推荐