Cod sursa(job #2389055)

Utilizator DovlecelBostan Andrei Dovlecel Data 26 martie 2019 19:31:29
Problema Diametrul unui arbore Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <fstream>
#include <vector>

using namespace std;
ifstream in("darb.in");
ofstream out("darb.out");
const int N=100005;
vector<int>a[N];
bool viz[N];
int n,d[N];

void dfs(int x)
{
    int y;
    viz[x]=true;
    for(unsigned i=0;i<a[x].size();i++)
    {
        y=a[x][i];
        if(!viz[y])
        {
            dfs(y);
            d[x]=max(d[x],d[y]+1);
        }
    }
}

int main()
{
    int x,y;
    in>>n;
    for(int i=1;i<n;i++)
    {
        in>>x>>y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    dfs(1);
    int max1=0,max2=0;
    for(unsigned i=0;i<a[1].size();i++)
    {
        if(d[a[1][i]]>=max1)
        {
            max2=max1;
            max1=d[a[1][i]];
        }
        else if(d[a[1][i]]>max2)
            max2=d[a[1][i]];
    }
    out<<max1+(bool)max1*1+max2+(bool)max2*1+1;
    return 0;
}