Cod sursa(job #2170564)

Utilizator LittleWhoFeraru Mihail LittleWho Data 15 martie 2018 08:19:52
Problema Diametrul unui arbore Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <bits/stdc++.h>

using namespace std;

const int nmax = static_cast<int>(1e5 + 1);
int dist[nmax];
int maxdist = 0;
int maxdist_node = 0;
vector<int> graph[nmax];
bitset<nmax> visited;

void dfs(int x, int d) {
    visited[x] = true;
    if (d > maxdist) {
        maxdist = d;
        maxdist_node = x;
    }

    for (auto &y: graph[x]) {
        if (!visited[y]) dfs(y, d + 1);
    }
}

int main() {
    freopen("carici.in", "r", stdin);

    freopen("darb.in", "r", stdin);
    freopen("darb.out", "w", stdout);

    int n;
    scanf("%d", &n);
    for (int i = 0, x, y; i < n - 1; i++) {
        scanf("%d%d", &x, &y);
        graph[x].push_back(y);
        graph[y].push_back(x);
    }

    dfs(1, 1);
    maxdist = 0;
    visited.reset();
    dfs(maxdist_node, 1);
    cout << maxdist << "\n";

    return 0;
}