Skip to content

Instantly share code, notes, and snippets.

@ravichandrae
Created July 18, 2014 12:36
Code Chef problem Permutation cycles.
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> perm(n);
int i;
for( i = 0; i < n; i++ )
{
cin >> perm[i];
}
int cycleCount = 0;
vector<bool> visited(n,false);
vector< vector<int> > cycles;
for( i = 0; i < n; i++ )
{
if( !visited[i] )
{
vector<int> cycle;
cycleCount++;
cycle.push_back(i);
int next = perm[i]-1;
while ( true )
{
cycle.push_back(next);
visited[next] = true;
if( next == i )
break;
next = perm[next]-1;
}
cycles.push_back(cycle);
}
}
cout << cycleCount << endl;
for( i = 0; i < cycles.size(); i++ )
{
for( int j = 0; j < cycles[i].size(); j++ )
cout << cycles[i][j]+1 << " ";
cout << endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment