Cod sursa(job #3137937)

Utilizator TaniaKallosKallos Tania TaniaKallos Data 16 iunie 2023 09:55:48
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;


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


const int N = 1e5;
int n;
int dist[N+1];
bool viz[N+1];
vector < vector <int> > v;


void dfs(int ns)
{
    queue <int> q;
    q.push(ns);

    while (!q.empty())
    {
        int a = q.front();
        q.pop();

        for (int i = 0; i < v[a].size(); i++)
        {
            int b = v[a][i];
            if (!viz[b])
            {
                viz[b] = 1;
                dist[b] = dist[a] + 1;
                q.push(b);
            }
        }
    }
}


int main()
{
    fin >> n;
    v.resize(n+1);

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


    dfs(1);

    int max1 = -1, p1;
    for (int i = 1; i <= n; i++)
    {
        if (dist[i] > max1)
        {
            max1 = dist[i];
            p1 = i;
        }
        dist[i] = 0;
        viz[i] = 0;
    }


    dfs(p1);

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

    fout << max2 + 1;


    return 0;
}