Cod sursa(job #2665678)

Utilizator Katherine456719Swan Katherine Katherine456719 Data 31 octombrie 2020 10:58:47
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <bits/stdc++.h>
using namespace std;

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

vector <int> graf[100005];
bool visited[100005];
queue <int> q;
int distances[100005], n, last;

void bfs(int node)
{
    visited[node] = true;
    q.push(node);
    while(!q.empty())
    {
        int x=q.front();
        q.pop();
        for(auto y : graf[x])
            if(!visited[y])
            {
                visited[y] = true;
                distances[y] = distances[x] + 1;
                last = y;
                q.push(y);
            }
    }
}

int main() {
     fin >> n;
     for(int i = 1; i <= n; ++i)
     {
         int a, b;
         fin >> a >> b;
         graf[a].push_back(b);
         graf[b].push_back(a);
     }
     bfs(1);
     for(int i = 1; i <= n; ++i)
        visited[i] = false;
     int x = last;
     bfs(last);
     fout << abs(distances[last] - distances[x]) + 1;
     return 0;
}