Cod sursa(job #2402843)

Utilizator radumihaisirbuSirbu Radu-Mihai radumihaisirbu Data 11 aprilie 2019 08:28:49
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>

using namespace std;

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

#define X first
#define Y second

const int nmax = 1e5 + 5;

bitset <nmax> viz;

vector <int> v[nmax];

int n, x, y, sol;

void bfs ()
{
    queue <int> q;

    int nod;

    viz[1] = 1;
    q.push(1);

    while (!q.empty())
    {
        nod = q.front();
        sol = nod;
        q.pop();
        for (vector <int> :: iterator it = v[nod].begin(); it!=v[nod].end(); ++it)
            if (!viz[*it])
            {
                viz[*it] = 1;
                q.push(*it);
            }
    }
}

int bfs2()
{
    queue <pair <int, int> > q;

    int nod, dist, SOL = 0;

    viz.reset();

    q.push(make_pair(sol, 1));

    viz[sol] = 1;

    while(!q.empty())
    {
        nod = q.front().X;
        dist = q.front().Y;
        SOL = dist;
        q.pop();

        for (vector <int> :: iterator it=v[nod].begin(); it!=v[nod].end(); ++it)
            if (!viz[*it])
            {
                viz[*it] = 1;
                q.push(make_pair(*it, dist + 1));
            }
    }

    return SOL;
}

int main()
{
    fin >> n;
    assert(n >= 1 && n < nmax);
    for (int i=1; i<n; ++i)
    {
        fin >> x >> y;
        assert(x >= 1 && x <= n);
        assert(y >= 1 && y <= n);
        v[x].push_back(y);
        v[y].push_back(x);
    }
    bfs();
    fout << bfs2();
    return 0;
}