Cod sursa(job #1244380)

Utilizator Andreid91Ciocan Andrei Andreid91 Data 17 octombrie 2014 10:52:08
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <vector>
#include <fstream>

using namespace std;

#define maxn 100003

vector<int > graf[maxn];
int lant[maxn], sw[maxn], best[maxn], n;

void solve(int nod) {
    sw[nod] = 1;
    lant[nod] = 1; best[nod] = 1;
    int max1 = 0, max2 = 0;
    for (vector<int > :: iterator it = graf[nod].begin(); it < graf[nod].end(); it ++) {
        if (sw[*it] == 1) {
                continue;
        }
        solve(*it);
        lant[nod] = max(lant[nod], lant[*it] + 1);
        best[nod] = max(best[nod], best[*it]);
        if (lant[*it] >= max1) {
            max2= max1;
            max1 = lant[*it];
        } else if (lant[*it] > max2) {
            max2 = lant[*it];
        }
    }
    best[nod] = max(best[nod], 1 + max2 + max1);
}

void afisare() {
    ofstream g ("darb.out");
    g << best[1];
    g.close();
}

void citire() {
    ifstream f("darb.in");
    f >> n ;
    for (int i = 1 ; i < n ; i++) {
        int x, y;
        f >> x >> y;
        graf[x].push_back(y);
        graf[y].push_back(x);
    }
    f.close();
}

int main()
{
    citire();
    solve(1);
    afisare();
    return 0;
}