Cod sursa(job #3376486)

Utilizator alex_0747Gheorghica Alexandru alex_0747 Data 17 noiembrie 2026 23:12:29
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.74 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

ifstream fin("darb.in");
ofstream fout("darb.out");

int n, mx;
vector<int> L[100005];

int DFS(int k, int p = 0, int d = 0)
{
    int mx1, mx2;
    mx1 = mx2 = d;
    for (int i : L[k]) {
        if (i == p) continue;
        int depth = DFS(i, k, d + 1);
        if (depth > mx1) {
            mx2 = mx1;
            mx1 = depth;
        } else if (depth > mx2) {
            mx2 = depth;
        }
    }
    mx = max(mx, mx1 + mx2 - 2 * d + 1);
    return mx1;
}

int main()
{
    int x, y;
    fin >> n;
    for (int i = 1; i < n; i++) {
        fin >> x >> y;
        L[x].push_back(y);
        L[y].push_back(x);
    }
    DFS(1);
    fout << mx << "\n";
    return 0;
}