Cod sursa(job #2641222)

Utilizator Stefan4814Voicila Stefan Stefan4814 Data 10 august 2020 16:46:32
Problema Diametrul unui arbore Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <bits/stdc++.h>
#define ll long long
#define NMAX 100005

using namespace std;

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

int n, last_node, max_dist;
bitset<NMAX> reached;
vector<int> dist(NMAX);
vector<int> edges[NMAX];

void bfs(int start_node) {
    queue<int> q;
    q.push(start_node);
    reached[start_node] = true;

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

        for(int i = 0; i < edges[node].size(); i++) {
            int neighbour = edges[node][i];
            if(!reached[neighbour]) {
                q.push(neighbour);
                reached[neighbour] = true;
                dist[neighbour] = dist[node] + 1;

                last_node = neighbour; //practic frunza
                max_dist = dist[neighbour];
            }
        }
    }
}

int main() {
    fin >> n;
    int m = n - 1;
    for(int i = 1; i <= m; i++) {
        int x, y;
        fin >> x >> y;
        edges[x].push_back(y);
        edges[y].push_back(x);
    }

    bfs(1);

    for (int i = 1; i <= n; i++)
        reached[i] = false;
    for (int i = 1; i <= n; i++)
        dist[i] = 0; ///aici ne "pregatim" pentru al doilea bfs.

    bfs(last_node);

    fout << max_dist + 1;
}