Cod sursa(job #3215720)

Utilizator PescarusTanislav Luca Andrei Pescarus Data 15 martie 2024 12:08:43
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.84 kb
#include <fstream>
#include <vector>
using namespace std;
const int nmax = 100005;
int sol, n;
int maxlen[nmax];
vector<int> l[nmax];
void dfs(int node, int father){
    int max1 = 0, max2 = 0;
    for(auto vec: l[node]){
        
        if(vec != father){
            dfs(vec, node);
            if(maxlen[vec] > max1){
                max2 = max1;
                max1 = maxlen[vec];
            }
            else if(maxlen[vec] > max2){
                max2 = maxlen[vec];
            }
        }
    }
    sol = max(sol, max1 + max2 + 1);
    maxlen[node] = max1 + 1;
}
int main(){
    ifstream f("darb.in");
    ofstream g("darb.out");
    f >> n;
    for(int i = 1; i <= n; i++){
        int x,y;
        f >> x >>y;
        l[x].push_back(y);
        l[y].push_back(x);
    }
    dfs(1, 0);
    g << sol << '\n';
}