Cod sursa(job #2676644)

Utilizator kitkat007Graphy kitkat007 Data 24 noiembrie 2020 18:41:18
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <map>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;

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

const int MAX_NODES_COUNT = 100013;

vector<int> adjList[MAX_NODES_COUNT];
int n, x, y;
int dist[MAX_NODES_COUNT];

void bfs(int s)
{
    queue<int> q;
    q.push(s);
    fill(dist, dist + n + 1, -1);
    dist[s] = 0;
    while (!q.empty())
    {
        int currNode = q.front();
        q.pop();
        for (int node : adjList[currNode])
        {
            if (dist[node] == -1)
            {
                dist[node] = dist[currNode] + 1;
                q.push(node);
            }
        }
    }
}

int main()
{
    fin >> n;
    for (int i = 1; i < n; ++i)
    {
        fin >> x >> y;
        adjList[x].push_back(y);
        adjList[y].push_back(x);
    }
    bfs(1);
    int maxVal = -1, maxIndex = -1;
    for (int i = 1; i <= n; ++i)
    {
        if (maxVal < dist[i])
        {
            maxVal = dist[i];
            maxIndex = i;
        }
    }
    bfs(maxIndex);
    for (int i = 1; i <= n; ++i)
    {
        maxVal = max(maxVal, dist[i]);
    }
    fout << maxVal + 1;
    fout.flush();
}