Cod sursa(job #3148394)

Utilizator andrei1807Andrei andrei1807 Data 31 august 2023 19:14:41
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.04 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

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

const int NMAX = 100003;

vector<int> g[NMAX];
int d[NMAX], dmax = 0, val = 1;

void bfs(const int& nod) {
    bool vis[NMAX] = {false};
    queue<int> q;
    q.push(nod);
    vis[nod] = true;

    while (!q.empty()) {
        int curr = q.front();
        q.pop();

        if (d[curr] > dmax) {
            dmax = d[curr];
            val = curr;
        }

        for (auto next : g[curr]) {
            if (!vis[next]) {
                d[next] = d[curr] + 1;
                vis[next] = true;
                q.push(next);
            }
        }
    }
}

int main() {

    int n;
    fin >> n;
    for (int i = 1; i <= n - 1; i++) {
        int x, y;
        fin >> x >> y;

        g[x].push_back(y);
        g[y].push_back(x);
    }

    bfs(1);

    int q = val;
    dmax = 0;
    val = 0;

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

    bfs(q);



    fout << dmax + 1;

    return 0;
}