15
3
There is a well-known theorem that any permutation can be decomposed into a set of cycles. Your job is to write the shortest possible program to do so.
Input:
Two lines. The first contains a number N
, the second contains N
distinct integers in the range [0,N-1]
separated by spaces. These integers represent a permutation of N
elements.
Output:
One line for each cycle in the permutation. Each line should be a space-separated list of integers in cycle order.
Cycles can be output in any order, and each cycle can be output starting at any position.
Example 1:
8
2 3 4 5 6 7 0 1
This input encodes the permutation 0->2, 1->3, 2->4, 3->5, 4->6, 5->7, 6->0, 7->1. This decomposes into cycles like this:
0 2 4 6
1 3 5 7
An equally valid output would be
5 7 1 3
2 4 6 0
Example 2:
8
0 1 3 4 5 6 7 2
valid output:
0
1
4 5 6 7 2 3
What is the point of having N in the input ? – Evpok – 2016-09-08T11:15:55.767
@Evpok: it's there in case it helps. No need to use it. – Keith Randall – 2016-09-28T20:32:22.673
@Keith What is the maximum value of N? – fR0DDY – 2011-03-17T17:34:15.367
33 chars in J :
>C.
– Eelvex – 2011-03-17T18:07:08.820Let's say N<1000. – Keith Randall – 2011-03-17T18:14:32.137
Permutations are usually counted up from 1, not 0. – Dr. belisarius – 2011-03-18T16:23:38.973
6Mathematicians count from 1, computer scientists count from 0 :) – Keith Randall – 2011-03-18T23:45:27.487
@Keith I count from 42 by exponential increasing increments. – Mateen Ulhaq – 2011-03-20T04:52:31.167
Nice problem, I thought of adding this one before but never got the right opportunity.Thanks :-) – Quixotic – 2011-03-22T01:07:17.867
I now remove my 38 chars solution. – aaaaaaaaaaaa – 2011-04-07T21:55:12.263