Cod sursa(job #2409918)

Utilizator Dragne.Andrei11Dragne Andrei Dragne.Andrei11 Data 19 aprilie 2019 15:53:30
Problema Diametrul unui arbore Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.05 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax=100005;

vector <int> a[nmax];

int nod, l;
int max_l;

bool visited[nmax];

void cle()
{
    for(int i=1;i<=nmax;i++)
        visited[i]=false;
}

void dfs(int start_node)
{
    visited[start_node]=true;
    for(int i=0;i<a[start_node].size();i++)
    {
        if(visited[a[start_node][i]]==false)
        {
            l++;
            if(l>max_l)
            {
                max_l=l;
                nod=a[start_node][i];
            }else if(max_l==l)
                nod=a[start_node][i];
            dfs(a[start_node][i]);
            l--;
        }
    }
}

int main()
{
    freopen("darp.in", "r", stdin);
    freopen("darp.out", "w", stdout);
    int n;

    scanf("%d", &n);
    for(int i=1;i<n;i++)
    {
        int x, y;
        scanf("%d%d", &x, &y);
        a[x].push_back(y);
        a[y].push_back(x);
    }
    l=max_l=0;
    nod=0;
    dfs(1);
    l=max_l=0;
    cle();
    dfs(nod);
    printf("%d\n", max_l+1);

    return 0;
}