Cod sursa(job #2641473)

Utilizator HermioneMatei Hermina-Maria Hermione Data 11 august 2020 16:13:28
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("darb.in");
ofstream g("darb.out");

vector<vector<int>> G;
vector<int> viz;
int n;

void read()
{
    f>>n;
    G.resize(n+1);
    viz.resize(n+1, 0);
    int x, y;
    while(f>>x>>y)
    {
        G[x].push_back(y);
        G[y].push_back(x);
    }
}

void dfs(int x)
{
    for(auto a:G[x])
        if(!viz[a])
        {
            viz[a]=viz[x]+1;
            dfs(a);
        }
}

int main()
{
    read();
    viz[1]=1;
    dfs(1);
    int x=INT_MIN, pos=0;
    for(int i=1; i<viz.size(); i++)
        if(viz[i]>x)
        {
            x=viz[i];
            pos=i;
        }
    viz.assign(n+1, 0);
    viz[pos]=1;
    dfs(pos);
    x=INT_MIN;
    for(int i=1; i<viz.size(); i++)
        if(viz[i]>x)
            x=viz[i];
    g<<x;
    return 0;
}