Cod sursa(job #2917711)

Utilizator elenacazaciocElena Cazacioc elenacazacioc Data 7 august 2022 12:31:13
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int INF = 100001;

vector<int> graph[100001];

int d[100001];
queue <int> q;

int n; // numarul de noduri din graf

void bfs(int node) {
    int i, x, y;

    for (i = 1; i <= n; i++) {
        d[i]= INF;
    }

    d[node] = 0;
    q.push(node);

    while(!q.empty()) {
        x = q.front(); // extrag nodul de la inceputul cozii
        q.pop(); // elimin nodul de la inceputul cozii

        // parcurg vecinii nodului x
        for (i = 0; i < graph[x].size(); i++) {
            y = graph[x][i];
            if (d[y] > 1 + d[x]) {
                d[y] = 1 + d[x];
                q.push(y);
            }
        }
    }
}

int main()
{
    int i, x, y;

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

    bfs(1);

    int dmax = d[1];
    int node_dmax = 1;
    for (i = 2; i <= n; i++) {
        if (d[i] > dmax) {
            dmax = d[i];
            node_dmax = i;
        }
    }

    // cout << dmax << " "<< node_dmax << '\n';

    bfs(node_dmax);

    int diametru = d[1];
    for (i = 2; i <= n; i++) {
        if (diametru < d[i]) {
            diametru = d[i];
        }
    }
    out << diametru + 1;

    return 0;
}