Cod sursa(job #1727604)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 11 iulie 2016 11:58:23
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

ifstream f("darb.in");
ofstream g("darb.out");

int x, y, i, cmlung, max1, n;
int dist[100002];
bool viz[100002];
vector <int> ls[100002];

struct muchie {
    int x, y;
}v[100005];

void bf(int X) {
    int i, x, y, l;
    queue <int> coada;
    coada.push(X);
    while (!coada.empty()) {
        x = coada.front();
        l = ls[x].size();
        coada.pop();
        for (i = 0; i < l; i++) {
            y = ls[x][i];
            if (viz[y] == 0) {
                viz[y] = 1;
                dist[y] = dist[x]+1;
                coada.push(y);
            }
        }
    }
}

int main() {
    f >> n;
    for (i = 1; i <= n; i++) {
        f >> x >> y;
        ls[x].push_back(y);
        ls[y].push_back(x);
    }
    bf(1);
    for (i = 1; i <= n; i++)
        if (dist[i] > max1) {
            max1 = dist[i];
            cmlung = i;
        }
    for (i = 1; i <= n; i++)
        dist[i] = viz[i] = 0;

    bf(cmlung);
    max1 = 0;
    for (i = 1; i <= n; i++)
        if (dist[i] > max1)
            max1 = dist[i];
    g << max1+1;
    return 0;
}