树的直径 图论

解法一 树形DP

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e5 + 10;
vector<int>e[N];
int n;
int ans;
int k[N];//k[i] 以i为根往下走最深
void dfs(int u, int fa, int d)
{
    for (int it : e[u])
    {
        if (it != fa)
        {
            dfs(it, u, d + 1);
            ans = max(ans, k[u] + 1 + k[it]);
            k[u] = max(k[u], k[it] + 1);
        }
    }
}
int main()
{
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    cin >> n;
    for (int i = 1; i <= n - 1; i++)
    {
        int x, y;
        cin >> x >> y;
        e[x].push_back(y);
        e[y].push_back(x);
    }
    dfs(1, 0, 0);
    cout << ans;
    return 0;
}

解法二 两次搜索

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 1e5 + 10;
vector<int>e[N];
int n;
int ans, id;
int k[N];//k[i] 以i为根往下走最深
void dfs(int u, int fa, int d)
{
    if (ans < d)
    {
        ans = d; id = u;
    }
    for (int it : e[u])
    {
        if (it != fa)
        {
            dfs(it, u, d + 1);
        }
    }
}
int main()
{
    ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
    cin >> n;
    for (int i = 1; i <= n - 1; i++)
    {
        int x, y;
        cin >> x >> y;
        e[x].push_back(y);
        e[y].push_back(x);
    }
    dfs(1, 0, 0);
    dfs(id, 0, 0);
    cout << ans;
    return 0;
}
posted @ 2025-01-24 16:08  闫柏军  阅读(23)  评论(0)    收藏  举报