Cod sursa(job #2445321)

Utilizator AlexandruGabrielAliciuc Alexandru AlexandruGabriel Data 3 august 2019 15:51:59
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <bits/stdc++.h>
#define N 100005

using namespace std;

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

int n, dist[N], dist_max = -1, capat;
bool gasit[N];
vector <int> L[N];

void DFS(int nod)
{
    gasit[nod] = 1;
    for (auto next_nod : L[nod])
    {
        if (!gasit[next_nod])
        {
            dist[next_nod] = dist[nod] + 1;
            DFS(next_nod);
        }
    }
}

int main()
{
    fin >> n;
    for (int i = 1; i < n; i++)
    {
        int a, b;
        fin >> a >> b;
        L[a].push_back(b);
        L[b].push_back(a);
    }

    DFS(1);
    for (int i = 1; i <= n; i++)
        if (dist[i] > dist_max)
        {
            dist_max = dist[i];
            capat = i;
        }
    for (int i = 1; i <= n; i++)
        dist[i] = gasit[i] = 0;
    DFS(capat);
    dist_max = -1;

    for (int i = 1; i <= n; i++)
        dist_max = max(dist_max, dist[i]);

    fout << dist_max + 1;
    return 0;
}