zcmu1369: Graph Theory (seeking the diameter of the tree)

Title link: https://acm.zcmu.edu.cn/JudgeOnline/problem.php?id=1369

Topic

Given a tree with N nodes, find out the distance (the diameter of the tree) between the two furthest points on this tree. The number of nodes on the tree ranges from 0-(N-1). The distance between all adjacent nodes is 1.

Ideas

First, take a random point to build a tree for the root node and run dfs. I took 0, then took the deepest node t, and then used t as the root to build a tree and run dfs. The maximum depth is the diameter of the tree.

ac code

#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;
}

 

Guess you like

Origin blog.csdn.net/weixin_43911947/article/details/113404667