Cod sursa(job #3347904)

Utilizator andreidebeliiDebelii andreidebelii Data 18 martie 2026 21:00:55
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <bits/stdc++.h>

using namespace std;
vector<int> adj[100005];
int depth[100005];
int max_d=0,pos=1;
void dfs(int u,int p){
    for(int v:adj[u]){
        if(v!=p){
            depth[v]=depth[u]+1;
            if(depth[v]>max_d){
                max_d=depth[v];
                pos=v;
            }
            dfs(v,u);
        }
    }
}
int main(){
    ifstream fin("darb.in");
    ofstream fout("darb.out");
    int n;
    fin>>n;
    for(int i =1;i<n;i++){
        int a,b;
        fin>>a>>b;
        adj[a].push_back(b);
        adj[b].push_back(a);

    }
    depth[1]=1;
    dfs(1,0);
    for(int i =1;i<=n;i++){
        depth[i]=0;
    }
    depth[pos]=1;
    max_d=0;
    dfs(pos,0);
    fout<<max_d;
    return 0;
}