Cod sursa(job #2693100)

Utilizator cristia_razvanCristia Razvan cristia_razvan Data 4 ianuarie 2021 19:51:05
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("darb.in");
ofstream fout("darb.out");
int n;
int d[100001];
vector<int> m[100001];
queue<int> q;
bitset<100001> viz;
void bfs(int x)
{
    viz.reset();
    q.push(x);
    viz[x] = 1;
    d[x] = 1;
    while (!q.empty())
    {
        x = q.front();
        q.pop();
        for (int i : m[x])
        {
            if (!viz[i])
            {
                d[i] = d[x] + 1;
                q.push(i);
                viz[i] = 1;
            }
        }
    }
}
int main()
{
    int x, y;
    fin >> n;
    for (int i = 1; i < n; i++)
    {
        fin >> x >> y;
        m[x].push_back(y);
        m[y].push_back(x);
    }
    bfs(1);
    int dMax = -1,pozmx = 0;
    for (int i = 1; i <= n; i++)
    {
        if (d[i] > dMax)
        {
            dMax = d[i];
            pozmx = i;
        }
    }
    bfs(pozmx);
    dMax = -1;
    for (int i = 1; i <= n; i++)
        dMax = max(dMax, d[i]);
    fout << dMax << "\n";
    fin.close();
    fout.close();
    return 0;
}