Cod sursa(job #3040903)

Utilizator IvanAndreiIvan Andrei IvanAndrei Data 30 martie 2023 16:36:02
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

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

const int max_size = 1e5 + 1;

vector <int> mc[max_size];
int viz[max_size], ans, ult;
queue <int> q;

void bfs (int src)
{
    q.push(src);
    viz[src] = 1;
    while (!q.empty())
    {
        int nod = q.front();
        q.pop();
        ult = nod;
        for (auto f : mc[nod])
        {
            if (!viz[f])
            {
                viz[f] = viz[nod] + 1;
                ans = max(ans, viz[f]);
                q.push(f);
            }
        }
    }
}

int main ()
{
    int n;
    in >> n;
    for (int i = 1; i < n; i++)
    {
        int x, y;
        in >> x >> y;
        mc[x].push_back(y);
        mc[y].push_back(x);
    }
    ans = 1;
    bfs(1);
    for (int i = 1; i <= n; i++)
    {
        viz[i] = 0;
    }
    bfs(ult);
    out << ans;
    in.close();
    out.close();
    return 0;
}