Cod sursa(job #3278871)

Utilizator mihai_bosIancu Mihai mihai_bos Data 20 februarie 2025 23:00:23
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.83 kb
#include <fstream>
#include <vector>
#include <climits>
using namespace std;

ifstream cin("darb.in");
ofstream cout("darb.out");

const int NMAX = 100005;

int n, maxi;
vector<int> v[NMAX];
int dp[NMAX];

void dfs(int node, int parent) {
    dp[node] = 1;
    int max1 = 0, max2 = 0;
    for (int x : v[node]) {
        if (x == parent) continue;
        dfs(x, node);
        if(dp[x] > max1) {
             max2 = max1;
             max1 = dp[x];
        }
        else if(dp[x] > max2)
            max2 = dp[x];
    }
    dp[node] = max1 + 1;
    maxi = max(maxi, max1 + max2 + 1);
}

int main() {
    cin >> n;

    for (int i = 1; i < n; i++) {
        int x, y;
        cin >> x >> y;
        v[x].push_back(y);
        v[y].push_back(x);
    }

    dfs(1, -1);
    cout << maxi;


    return 0;
}