Cod sursa(job #3143934)

Utilizator emazareMazare Emanuel emazare Data 3 august 2023 12:33:29
Problema Diametrul unui arbore Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.02 kb
#include <fstream>
#include <vector>
#include <climits>

using namespace std;

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

const int Nmax = 100005;
int diam[Nmax],lant[Nmax];
vector<int> L[Nmax];

void dfs(int node, int father){
    for(int son : L[node]){
        if(son!=father)
            dfs(son, node);
    }
    int max1 = 0, max2 = 0;
    lant[node] = 1;
    for(int son : L[node]){
        if(son!=father){
            lant[node] = max(lant[node],lant[son]+1);
            diam[node] = max(diam[node], lant[node]);
            if(lant[son]>max1){
                max2 = max1;
                max1 = lant[son];
            }
            else if(lant[son]>max2)
                max2 = lant[son];
        }
    }
    diam[node] = max(diam[node],max1+max2+1);
}

int main()
{
    int n,i;
    fin >> n;
    for(i=1;i<n;i++){
        int x,y;
        fin >> x >> y;
        L[x].push_back(y);
        L[y].push_back(x);
    }
    dfs(1, 0);
    fout << diam[1];
    return 0;
}