Cod sursa(job #3214919)

Utilizator SerbanCaroleSerban Carole SerbanCarole Data 14 martie 2024 16:03:20
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.07 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
using pii = pair<int,int>;
ifstream cin("darb.in");
ofstream cout("darb.out");
const int nmax = 1e5 + 1;
int n , x , y , dp[nmax];
bool viz[nmax];
vector <int> g[nmax];
signed main()
{
    cin >> n;
    for(int i = 1 ; i < n ; ++i)
    {
        cin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }
    queue<int>q;
    viz[1] = 1;
    q.push(1);
    int last = -1;
    while(!q.empty())
    {
        x = q.front();
        q.pop();
        last = x;
        for(auto it : g[x])
        {
            if(!viz[it])
            {
                viz[it] = 1;
                q.push(it);
            }
        }
    }
    dp[last] = 1;
    q.push(last);
    while(!q.empty())
    {
        x = q.front(); q.pop();
        last = x;
        for(auto it : g[x])
        {
            if(!dp[it])
            {
                dp[it] = dp[x] + 1;
                q.push(it);
            }
        }
    }
    cout << dp[last];
    return 0;
}