DMOJ · dmopc14c4p6

Save Nagato

This C++ solution uses graph traversal for DMOJ dmopc14c4p6 Save Nagato. Read the reasoning, inspect the code, or try your own test case below.

dmopc14c4p6Graphs & treesGraph traversalC++52 lines
Solution181of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Graph traversal

Save Nagato matches the tree input and the code's per-node farthest-distance result.

Graphs & trees

Problem and code

Useful links.

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

Open official problem ↗View exact source file ↗
Implementation

save_nagato.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
     
    pair<int, vector<int>> bfs(int start, const vector<vector<int>> &g){
        int n = g.size() - 1;
        vector<int> d(n + 1, -1);
        queue<int> q;
        d[start] = 0; q.push(start);
        int far = start;
        while(!q.empty()){
            int u = q.front(); q.pop();
            if(d[u] > d[far]) far = u;
            for(int v : g[u]){
                if(d[v] == -1){
                    d[v] = d[u] + 1;
                    q.push(v);
                }
            }
        }
        return {far, d};
    }
     
    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 << 1 << "\n";
            return 0;
        }
        //farthest from 1 -> A
        auto [A, d1] = bfs(1, g);
        //farthest from A -> B, also get dist from A
        auto tmp = bfs(A, g);
        int B = tmp.first;
        vector<int> distA = move(tmp.second);
        //dist from B
        auto tmp2 = bfs(B, g);
        vector<int> distB = move(tmp2.second);
        // For each node v, answer = max(distA[v], distB[v]) + 1
        for(int v = 1; v <= n; v++){
            cout << max(distA[v], distB[v]) + 1 << "\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.