Cod sursa(job #2145424)

Utilizator calinfloreaCalin Florea calinflorea Data 27 februarie 2018 12:49:41
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <bits/stdc++.h>
#define NMax 100006

using namespace std;

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

vector <int> L[NMax];
int n;
bool viz[NMax];
int t[NMax];

void Citire()
{
    int i, x, y;

    fin >> n;

    for(i = 1; i <= n; i++)
    {
        fin >> x >> y;
        L[x].push_back(y);
        L[y].push_back(x);
    }
}

void DFS1(int nod)
{
    int i, j;

    viz[nod] = 1;

    for(j = 0; j < L[nod].size(); j++)
    {
        i = L[nod][j];
        if(!viz[i])
        {
            t[i] = t[nod] + 1;
            DFS1(i);
        }
    }
}

void DFS2(int nod)
{
    int i, j;

    viz[nod] = 1;

    for(j = 0; j < L[nod].size(); j++)
    {
        i = L[nod][j];
        if(!viz[i])
        {
            t[i] = t[nod] + 1;
            DFS2(i);
        }
    }
}

inline void Rezolva()
{
    int i, x = 0, y;

    for(i = 1; i <= n; i++)
        t[i] = 1;
    DFS1(1);

    for(i = 1; i <= n; i++)
    {
        if(x < t[i])
        {
            x = t[i];
            y = i;
        }
        viz[i] = 0;
        t[i] = 1;
    }
    DFS2(y);
    x = 0;

    for(i = 1; i <= n; i++)
        x = max(x, t[i]);
    fout << x << "\n";
}
int main()
{
    Citire();
    Rezolva();
    return 0;
}