Cod sursa(job #2575357)

Utilizator BogdanRazvanBogdan Razvan BogdanRazvan Data 6 martie 2020 13:03:32
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <bits/stdc++.h>

using namespace std;

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

void usain_bolt()
{
    ios::sync_with_stdio(false);
    fin.tie(0);
}

const int N = 1e5 + 5;

vector < int > a[N], d(N);

void bfs(int k)
{
    d.assign(N - 2, 2e9);
    queue < int > q;
    d[k] = 0;
    q.push(k);
    while(!q.empty()) {
        int x = q.front();
        q.pop();
        for(auto v : a[x]) {
            if(d[v] > d[x] + 1) d[v] = d[x] + 1, q.push(v);
        }
    }
}

int main()
{
    usain_bolt();

    int n;

    fin >> n;
    for(int i = 1; i < n; ++i) {
        int x, y;

        fin >> x >> y;
        a[x].push_back(y);
        a[y].push_back(x);
    }

    bfs(1);
    int mx = 0, pos = -1;
    for(int i = 1; i <= n; ++i) {
        if(d[i] > mx) pos = i;
        mx = max(mx, d[i]);
    }
    bfs(pos);
    mx = 0;
    for(int i = 1; i <= n; ++i) mx = max(mx, d[i]);
    fout << mx + 1;
    return 0;
}