1. 程式人生 > >hihoCoder week11 樹中的最長路

hihoCoder week11 樹中的最長路

hihocoder sca clu nbsp 題目 節點 amp printf c++

題目鏈接: https://hihocoder.com/contest/hiho11/problem/1

求樹中節點對 距離最遠的長度

#include <bits/stdc++.h>
using namespace std;

const int N = 1e5 + 10;
int n;
vector<int> G[N];
int d[N];
void dfs(int u, int fa)
{
    for(int i=0; i<G[u].size(); i++) {
        int v = G[u][i];
        if(v != fa) {
            d[v] 
= d[u] + 1; dfs(v, u); } } } int main() { freopen("in.txt", "r", stdin); scanf("%d",&n); for(int i=0; i<n-1; i++) { int a,b; scanf("%d %d", &a, &b); G[a].push_back(b); G[b].push_back(a); } d[1] = 0; dfs(
1, 0); int mx = 0; int index = -1; for(int i=1; i<=n; i++) { if(mx < d[i]) { mx = d[i]; index = i; } } //printf("%d\n", mx); memset(d,0,sizeof(d)); dfs(index, 0); for(int i=1; i<=n; i++) { if(mx < d[i]) { mx
= d[i]; index = i; } } cout << mx <<endl; return 0; }

#include <bits/stdc++.h>
using namespace std;

const int N = 1e5 + 10;
vector<int> G[N];
int n, ans;

int dfs(int u,int fa)
{
    int l1=-1,l2=-1;
    for(int i=0; i<G[u].size(); i++) {
        int v = G[u][i]; 
        if(v == fa) continue;
        int l = dfs(v, u);
        if(l > l1) 
            l2=l1 , l1=l;
        else 
            l2 = max(l2, l);
        
    }
    //cout << u <<" "<< l1 <<" "<< l2 <<endl;
    ans = max(ans , l1 + l2 + 2);
    // cout << u <<" 最長的路為" <<l1 <<endl;
    return l1+1;
}


int main()
{
    //freopen("in.txt", "r", stdin);
    cin >> n;
    for(int i=1; i<n; i++) {
        int a,b; scanf("%d %d", &a, &b);
        G[a].push_back(b);
        G[b].push_back(a);
    }
    ans = 0;
    dfs(1,0);
    cout << ans <<endl;
    return 0;
}

hihoCoder week11 樹中的最長路