Last active
October 14, 2019 18:14
-
-
Save karngyan/5d8bfd89d91525a66b928e8021093dad to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
author: @karngyan | |
Team: BlundersPride | |
*/ | |
#include<bits/stdc++.h> | |
using namespace std; | |
const int N = 1005; | |
int a[N]; | |
int main() | |
{ | |
int n; | |
cin >> n; | |
// approach: | |
// for each index we will find the cycle starting from that | |
// ignoring indices which are part of some other cycle | |
// visited array denotes that if an index | |
// is visited i.e. its part of some cycle we | |
// will not check a cycle starting from that index | |
vector<bool> visited(n+1, false); | |
// vector of vectors will contain all cycles we find | |
vector< vector<int> > all_cycles; | |
for (int i = 1 ; i <= n ; ++i) | |
cin >> a[i]; | |
for (int i = 1 ; i <= n ; ++i) { | |
if (!visited[a[i]]) { | |
vector<int> cycle; | |
cycle.push_back(i); | |
int next = a[i]; | |
visited[i] = true; | |
while (next != i) { | |
cycle.push_back(next); | |
visited[next] = true; | |
next = a[next]; | |
} | |
cycle.push_back(next); | |
all_cycles.push_back(cycle); | |
} | |
} | |
int k = all_cycles.size(); | |
cout << k << "\n"; | |
for (auto cycle : all_cycles) { | |
for (auto i : cycle) | |
cout << i << " "; | |
cout << "\n"; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment