Codeforces
CF Step
Youtube Linkedin Discord Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Code

#include <bits/stdc++.h>
using namespace std;

vector<int> bfs(vector<vector<int>> &adj, int src) {
    int n = adj.size();

    queue<int> q;
    vector<int> level(n, -1);
    level[src] = 0;
    q.push(src);

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

        for (auto child : adj[now]) {
            if (level[child] == -1) {
                level[child] = level[now] + 1;
                q.push(child);
            }
        }
    }

    return level;
}

int solve(vector<vector<int>> &adj) {
    int n = adj.size();
    vector<int> dist = bfs(adj, 0);
    int mx = -1, farthest_node = -1;
    for (int i = 0; i < n; i++) {
        if (mx < dist[i]) {
            mx = dist[i];
            farthest_node = i;
        }
    }

    dist = bfs(adj, farthest_node);
    int diameter = 0;
    for (int i = 0; i < n; i++) {
        diameter = max(diameter, dist[i]);
    }

    return diameter;
}

int main() {
    int n;
    cin >> n;

    vector<vector<int>> adj(n);
    for (int i = 0; i < (n - 1); i++) {
        int u, v;
        cin >> u >> v;
        u--;
        v--;
        adj[u].push_back(v);
        adj[v].push_back(u);
    }

    cout << solve(adj) << "\n";
}