Cod sursa(job #1428245)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 3 mai 2015 22:38:07
Problema Diametrul unui arbore Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>
#include <vector>
#include <deque>
#include <cstring>

using namespace std;

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

int viz[100001], mlc, n, dist[100001], a, b, i, node, maxx, temp;
vector <int> gr[100001];
deque<int> q;

void bfs(int node, int& maxx, int& maxx_node)
{
    viz[node] = 1;
    q.push_back(node);
    while (!q.empty())
    {
        mlc++;
        int x = q.front();
        for (auto it : gr[x])
            if (!viz[it])
            {
                viz[it] = 1;
                dist[it] = dist[x] + 1;
                if (dist[it] > maxx)
                {
                    maxx = dist[it];
                    maxx_node = it;
                }
                q.push_back(it);
            }
        q.pop_front();
    }
}

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

    bfs(1, maxx, node);
    if (mlc > n)while (1);

    memset(viz, 0, sizeof(viz));
    memset(dist, 0, sizeof(dist));
    maxx = 0;

    bfs(node, maxx, temp);

    fout << maxx + 1;

    return 0;
}