Cod sursa(job #1755131)

Utilizator SaitamaSaitama-san Saitama Data 9 septembrie 2016 14:48:51
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.91 kb
#include <bits/stdc++.h>
#define nmax 100005

using namespace std;

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

int n, sol, dp[100005];
vector <int> L[nmax];

void Read()
{
    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);
    }
    fin.close();
}

void DFS(int nod, int tata)
{
    int i, max1, max2, Nnod;
    max1 = max2 = 0;
    for(i = 0; i < L[nod].size(); i++)
    {
        Nnod = L[nod][i];
        if(Nnod == tata) continue;
        DFS(Nnod,nod);
        if(dp[Nnod] > max1)
        {
            max2 = max1;
            max1 = dp[Nnod];
        }
        else if(dp[Nnod] > max2) max2 = dp[Nnod];
    }
    dp[nod] = max1 + 1;
    sol = max(sol, max1 + max2 + 1);
}

int main()
{
    Read();
    DFS(1,0);
    fout << sol << "\n";
    fout.close();
    return 0;
}