C++ · Solution

Jaden Studies Trees

This C++ solution uses graph traversal for Jaden Studies Trees. Read the reasoning, inspect the code, or try your own test case below.

Graphs & treesGraph traversalC++40 lines
Solution116of 248
Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Graph traversal

Jaden Studies Trees: explore states in breadth-first order with a queue, marking each state when it is reached so every vertex and edge is processed only as needed.

Breadth-first searchGraphs

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

View exact source file ↗
Implementation

jaden_studies_trees.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    pair<int,int> bfs(int start, const vector<vector<int>> &g){
        int n = g.size() - 1;
        vector<int> dist(n + 1, -1);
        queue<int> q;
        dist[start] = 0; q.push(start);
        int far = start;
        while(!q.empty()){
            int u = q.front(); q.pop();
            if(dist[u] > dist[far]) far = u;
            for(int v : g[u]){
                if(dist[v] == -1){
                    dist[v] = dist[u] + 1;
                    q.push(v);
                }
            }
        }
        return {far, dist[far]};
    }
    int main(){
        ios::sync_with_stdio(0);
        cin.tie(0);
        int n; cin >> n;
        vector<vector<int>> g(n + 1);
        for(int i = 0; i < n - 1; i++){
            int u, v; cin >> u >> v;
            g[u].push_back(v);
            g[v].push_back(u);
        }
        if(n == 1){
            cout << 0 << "\n";
            return 0;
        }
        auto a = bfs(1, g);
        auto d = bfs(a.first, g);
        cout << d.second << "\n";
        return 0;
    }
     
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.