Cod sursa(job #2965092)

Utilizator domistnSatnoianu Dominic Ioan domistn Data 14 ianuarie 2023 14:08:38
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.86 kb
#include <bits/stdc++.h>

using namespace std;

const int NMAX = 1e5;

int n, nod1, niv[NMAX + 1], ans;
vector<int> adj[NMAX + 1];

void firstDfs(int nod = 1, int par = 0) {
    niv[nod] = niv[par] + 1;
    if(niv[nod1] < niv[nod]) nod1 = nod;
    for(const auto &el : adj[nod]) {
        if(el == par) continue;
        firstDfs(el, nod);
    }
}

void secondDfs(int nod = nod1, int par = 0, int ln = 1) {
    ans = max(ans, ln);
    for(const auto &el : adj[nod]) {
        if(el == par) continue;
        secondDfs(el, nod, ln + 1);
    }
}

int main()
{
    freopen("darb.in", "r", stdin);
    freopen("darb.out", "w", stdout);
    cin >> n;
    for(int i = 1, x, y; i <= n; ++i) {
        cin >> x >> y;
        adj[x].push_back(y);
        adj[y].push_back(x);
    }
    firstDfs();
    secondDfs();
    cout << ans;
    return 0;
}