Cod sursa(job #3334052)

Utilizator NeamtuMateiNeamtu Matei-Constantin NeamtuMatei Data 15 ianuarie 2026 22:12:45
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.06 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

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

const int MAXN = 1e5;

int n, x, y, _;
int diametru;
bool viz[MAXN+1];
vector<int> graf[MAXN+1];

void dfs(int nod, int depth, int &_nod, int &_max_depth) {
    if (depth > _max_depth)
        _max_depth = depth,
        _nod = nod;

    viz[nod] = true;

    for (auto e: graf[nod])
        if (!viz[e])
            dfs(e, depth + 1, _nod, _max_depth);
}

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

    int nod_deep1, adancime_max1 = 0;
    dfs(1, 1, nod_deep1, adancime_max1); // oricare nod -> luam nodul 1

    // dfs din cel mai adanc nod, iar adancimea maxima de data aceasta
    // va reprezenta diametrul
    for (int i = 1; i <= n; i++)
        viz[i] = false;

    diametru = 0;
    dfs(nod_deep1, 1, _, diametru);

    out << diametru;

    return 0;
}