Cod sursa(job #2999222)

Utilizator Chiri_Robert Chiributa Chiri_ Data 10 martie 2023 17:41:04
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.79 kb
#include <bits/stdc++.h>

using namespace std;

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

int n, x, y, lung;
vector<int> g[100001];

pair<int, int> dfs(int st, int p = -1, int k = 0) {
    int lmx = k, xmx = st;

    for (auto& x : g[st]) {
        if (x != p) {
            auto t = dfs(x, st, k + 1);
            if (t.first > lmx) {
                lmx = t.first;
                xmx = t.second;
            }
        }
    }

    return make_pair(lmx, xmx);
}

int main() {
    fin >> n;
    for (int i = 1; i < n; i++) {
        fin >> x >> y;
        g[x].push_back(y);
        g[y].push_back(x);
    }

    auto st = dfs(1);
    // fout << st.first << " " << st.second << endl;
    auto sf = dfs(st.second);
    // fout << sf.first << " " << sf.second << endl;
    fout << sf.first + 1;
}