Tuesday, December 24, 2013

codechef PCYCLE - "permutation cycles" solution

codechef PCYCLE - "permutation cycles": http://www.codechef.com/problems/PCYCLE

codechef PCYCLE - "permutation cycles" solution: http://ideone.com/7JzmTr

#include <iostream>
using namespace std;

int main() {
// your code goes here
int n, arr[1005], a, b[2005], count=0;
cin>>n;
for(int i=1; i<=n; i++) cin>>arr[i];
for(int i=1; i<=2005; i++) b[i]=true;
for(int i=1; i<=n; i++) {
if(b[i]) {
count++;
b[i]=false; a=arr[i];
while(a!=i) {b[a]=false; a=arr[a];}
}
}
cout<<count<<endl;
for(int i=1; i<=2005; i++) b[i]=true;
for(int i=1; i<=n; i++) {
if(b[i]) {
cout<<i<<" "; b[i]=false; a=arr[i]; cout<<a;
while(a!=i) {b[a]=false; a=arr[a]; cout<<" "<<a;}
cout<<endl;
}
}
return 0;
}

codechef PCYCLE - "permutation cycles" guidance: 

take an boolean array b[2005], initialize to true all indice of b[]. start from i=1 and go to the last index(here n). make it false(b[i]=false). set a=arr[i], and loop it with while(a!=i). here we use "a" just to represent the value of index "i". everytime you encounter b[i]==true, increase counter(count++). at the end print out it(cout<<count). and then again from beginning print out the rest of array, with endlines or spaces when necessary.

No comments:

Post a Comment