File tree Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Expand file tree Collapse file tree 1 file changed +81
-0
lines changed Original file line number Diff line number Diff line change 1+ #include < bits/stdc++.h>
2+ using namespace std ;
3+
4+ int n, m;
5+ vector<vector<int >> adj;
6+ vector<bool > visited;
7+ vector<int > parent;
8+ int cycle_start, cycle_end;
9+
10+ bool isCycle (int v, int p)
11+ {
12+ visited[v] = true ;
13+ for (int child : adj[v])
14+ {
15+ if (child == p)
16+ continue ; // Skip the parent node
17+ if (visited[child])
18+ {
19+ cycle_end = v;
20+ cycle_start = child;
21+ return true ;
22+ }
23+ parent[child] = v;
24+ if (isCycle (child, v))
25+ {
26+ return true ;
27+ }
28+ }
29+ return false ;
30+ }
31+
32+ int main ()
33+ {
34+ ios::sync_with_stdio (false );
35+ cin.tie (nullptr );
36+ cin >> n >> m;
37+ adj.resize (n);
38+ for (int i = 0 ; i < m; i++)
39+ {
40+ int u, v;
41+ cin >> u >> v;
42+ u--;
43+ v--;
44+ adj[u].push_back (v);
45+ adj[v].push_back (u);
46+ }
47+ visited.assign (n, false );
48+ parent.assign (n, -1 );
49+ cycle_start = -1 ;
50+ for (int v = 0 ; v < n; v++)
51+ {
52+ if (!visited[v] && isCycle (v, parent[v]))
53+ break ;
54+ }
55+
56+ if (cycle_start == -1 )
57+ {
58+ cout << " IMPOSSIBLE" << ' \n ' ;
59+ }
60+ else
61+ {
62+ vector<int > cycle;
63+ cycle.push_back (cycle_start);
64+ for (int v = cycle_end; v != cycle_start; v = parent[v])
65+ {
66+ cycle.push_back (v);
67+ }
68+ cycle.push_back (cycle_start);
69+ cout << cycle.size () << ' \n ' ;
70+ for (int v : cycle)
71+ {
72+ cout << v + 1 << ' ' ;
73+ }
74+ }
75+ return 0 ;
76+ }
77+
78+ // Time Complexity: O(n + m) where n is number of nodes and m is number of edges
79+ // Space Complexity: O(n + m) for adjacency list and O(n) for visited and parent arrays
80+
81+ // Problem link: https://cses.fi/problemset/task/1669/
You can’t perform that action at this time.
0 commit comments