DMOJ · dwite09c1p5

Running In Circles

This C++ solution uses graph traversal for DMOJ dwite09c1p5 Running In Circles. Read the reasoning, inspect the code, or try your own test case below.

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

Approach

Graph traversal

Running In Circles matches five directed functional graphs and the required cycle-length outputs.

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

running_in_circles.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    vector<vector<int>> adj;
    vector<int> color, depth, parent;
    int ans = -1;
    void dfs(int u){
        color[u] = 1; // visiting
        for (int v : adj[u]){
            if (ans != -1) return; // cycle already found
            if (color[v] == 0){
                parent[v] = u;
                depth[v] = depth[u] + 1;
                dfs(v);
            } else if (color[v] == 1){
                ans = depth[u] - depth[v] + 1; // foudn unique cycle
                return;
            }
        }
        color[u] = 2; // done
    }
     
    int main(){
        ios::sync_with_stdio(0);
        cin.tie(0);
        for (int tc = 0; tc < 5; tc++){
            int m; cin >> m;
            adj.assign(101, {});
            color.assign(101, 0);
            depth.assign(101, 0);
            parent.assign(101, -1);
            ans = -1;
            int start = -1;
            for (int i = 0; i < m; i++){
                int u, v; cin >> u >> v;
                if (i == 0) start = u;
                adj[u].push_back(v);
            }
            dfs(start);
            cout << ans << "\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.