Cod sursa(job #3309204)

Utilizator razvanmrt_06Mariuta Razvan razvanmrt_06 Data 2 septembrie 2025 15:28:46
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.87 kb
#include <fstream>
#include <vector>

using namespace std;

const int Nmax = 100005;

int n, sol, depthMax[Nmax];
vector<int> L[Nmax];

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

int main(){
    ifstream fin("darb.in");
    ofstream fout("darb.out");
    fin >> n;
    for(int 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 << sol;

    return 0;
}