Cod sursa(job #2216041)

Utilizator TheNextGenerationAyy LMAO TheNextGeneration Data 24 iunie 2018 18:50:53
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.93 kb
#include <bits/stdc++.h>

using namespace std;

ifstream in("darb.in");
ofstream out("darb.out");
const int NMAX = 100005;
vector<int> v[NMAX];
int dist[NMAX];
int d,last;
void bfs(int b)
{
    queue<int> q;
    q.push(b);
    while (!q.empty())
    {
        int now = q.front();
        q.pop();
        for (auto it: v[now])
        {
            if (!dist[it])
            {
                dist[it] = 1+dist[now];
                if (dist[it]>d)
                {
                    d = dist[it];
                    last = it;
                }
                q.push(it);
            }
        }
    }
}

int main()
{
    int n;
    in >> n;
    for (int i = 1; i<n; i++)
    {
        int x,y;
        in >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }
    dist[1] = 1;
    bfs(1);
    memset(dist,0,sizeof(dist));
    dist[last] = 1;
    bfs(last);
    out << d;
}