Cod sursa(job #2116809)

Utilizator FredyLup Lucia Fredy Data 27 ianuarie 2018 23:34:05
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

#define lim 100010
#define inf 2e9
int n;
vector <int> G[lim];
int path[lim];

int bfs (int nod)
{
    for (int i=1; i<=n; i++)    path[i]=inf;
    queue <int> q;
    path[nod] = 1;
    q.push(nod);

    while (!q.empty())
    {
        int act = q.front();
        q.pop();
        for (auto it:G[act])
            if (path[it]==inf)
            {
                path[it] = path[act] + 1;
                q.push (it);
            }
    }
}

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

    bfs (x);
    int maxm=x;
    for (int i=1; i<=n; i++)
        if (path[i] != inf && path[i] > path[maxm])
            maxm=i;

    bfs (maxm);
    for (int i=1; i<=n; i++)
        if (path[i] != inf && path[i] > path[maxm]) maxm=i;

    fout<<path[maxm];
    return 0;
}