From f869a20cf7a814a6e5bf48f43d4bd94f7574239f Mon Sep 17 00:00:00 2001 From: AYUSH KUMAR GUPTA Date: Wed, 22 Oct 2025 15:58:18 +0530 Subject: [PATCH] solution for the Round Trip problem in graph algorithms --- 4_graph_algorithms/Round-Trip.cpp | 81 +++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 4_graph_algorithms/Round-Trip.cpp diff --git a/4_graph_algorithms/Round-Trip.cpp b/4_graph_algorithms/Round-Trip.cpp new file mode 100644 index 0000000..2daffe5 --- /dev/null +++ b/4_graph_algorithms/Round-Trip.cpp @@ -0,0 +1,81 @@ +#include +using namespace std; + +int n, m; +vector> adj; +vector visited; +vector parent; +int cycle_start, cycle_end; + +bool isCycle(int v, int p) +{ + visited[v] = true; + for (int child : adj[v]) + { + if (child == p) + continue; // Skip the parent node + if (visited[child]) + { + cycle_end = v; + cycle_start = child; + return true; + } + parent[child] = v; + if (isCycle(child, v)) + { + return true; + } + } + return false; +} + +int main() +{ + ios::sync_with_stdio(false); + cin.tie(nullptr); + cin >> n >> m; + adj.resize(n); + for (int i = 0; i < m; i++) + { + int u, v; + cin >> u >> v; + u--; + v--; + adj[u].push_back(v); + adj[v].push_back(u); + } + visited.assign(n, false); + parent.assign(n, -1); + cycle_start = -1; + for (int v = 0; v < n; v++) + { + if (!visited[v] && isCycle(v, parent[v])) + break; + } + + if (cycle_start == -1) + { + cout << "IMPOSSIBLE" << '\n'; + } + else + { + vector cycle; + cycle.push_back(cycle_start); + for (int v = cycle_end; v != cycle_start; v = parent[v]) + { + cycle.push_back(v); + } + cycle.push_back(cycle_start); + cout << cycle.size() << '\n'; + for (int v : cycle) + { + cout << v + 1 << ' '; + } + } + return 0; +} + +//Time Complexity: O(n + m) where n is number of nodes and m is number of edges +//Space Complexity: O(n + m) for adjacency list and O(n) for visited and parent arrays + +//Problem link: https://cses.fi/problemset/task/1669/ \ No newline at end of file