Cod sursa(job #1585405)

Utilizator theodor.moroianuTheodor Moroianu theodor.moroianu Data 30 ianuarie 2016 23:24:46
Problema Diametrul unui arbore Scor 80
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>
#include <vector>
using namespace std;

vector <int> a[100001];
int d[100001]; /// adancimea maxima din nodul i in jos
int lmax = 0;

void f(int nod, int tata);

int main() {
    int n, x, y;
    ifstream in("darb.in");
    in >> n;
    while (--n) {
        in >> x >> y;
        a[x].push_back(y);
        a[y].push_back(x);
    }
    f(1, -1);
    ofstream out("darb.out");
    out << lmax;
    return 0;
}

void f(int nod, int tata) {
    int l = 0, lsec = 0;
    for (auto i : a[nod]) {
        if (i == tata)
            continue;
        f(i, nod);
        if (d[i] > l) {
            lsec = l;
            l = d[i];
        }
        else if (d[i] > lsec)
            lsec = d[i];
    }
    if (l + lsec > lmax)
        lmax = l + lsec + 1;
    d[nod] = l + 1;
}