Cod sursa(job #2832915)

Utilizator robertanechita1Roberta Nechita robertanechita1 Data 14 ianuarie 2022 14:51:23
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <bits/stdc++.h>

using namespace std;

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

int d[100005], n, viz[100005], p;
vector<int>h[100005];

void Dfs(int i)
{
    viz[i] = 1;
    for(auto j : h[i])
        if(viz[j] == 0)
    {
        d[j] = d[i] + 1;
        Dfs(j);
    }
}

void Solve()
{
    d[1] = 1;
    Dfs(1);
    for(int i = 1; i <= n; i++)
        if(d[i] > d[p])
            p = i;
    for(int i = 1; i <= n; i++)
        viz[i] = d[i] = 0;
    d[p] = 1;
    Dfs(p);
    p = 0;
    for(int i = 1; i <= n; i++)
        if(d[i] > d[p])
            p = i;
    fout << d[p];
}


int main()
{
    int x, y;
    fin >> n;
    for(int i = 1; i < n; i++)
    {
        fin >> x >> y;
        h[x].push_back(y);
        h[y].push_back(x);
    }
    Solve();
    return 0;
}