Title Link: https://hihocoder.com/problemset/problem/1330
Time limit: 10000ms single point time limit: 1000ms memory limit: 256MB description
Little hi wants to know if he rearrange the array in a fixed order every time, then the array will revert to the initial order after a few reflow times.
Specifically, given a 1-to-one N arrangement P , the small hi each reflow is to put the first element in the first i Pi position. For example, P = (2, 3, 1), assuming that the initial array is (1, 2, 3), is re-ranked once (3, 1, 2), re-ranked two times and then changed to (2, 3, 1), re-ranked three times back (1, 2, 3).
The elements in the row array can be considered to be 22 different.
Input
The first line is an integer N that represents the length of the array. (1≤ N ≤100)
The second row of N integers, representing N an arrangement of 1- P .
Output
The minimum number of reflow times to output.
(PS. From the actual submitted AC code, it seems that the number of rearrangement is at least 1, that is, must be re-scheduled operation)
-
Sample input
-
32 3 1
-
Sample output
-
3
Exercises
It is not difficult to see, any one number, it can go back to the original position by a finite number of steps;
Then, we according to P= (2,3,1), then the initial sequence number first a[1], after the first step, it will change to the second, after the second operation it will change to the third position, the third step will change back to the first position, that is, back to the original position;
If the actual meaning of the operation is ignored, simply from the digital transformation, namely 1→2→3→1, three arrows, representing the operation of three steps;
So more extensive, for example p= (5,2,1,4,3,6), for each bit there are:
1→5→3→1 (3 steps);
2→2 (1 steps);
3→1→5→3 (3 steps);
......
5→3→1→5 (3 steps);
6→6 (1 steps);
Then I did this step to guess is not to enumerate each bit to the minimum number of steps to return to the original position, the maximum value can be;
There are, however, obvious counter-examples, such as p= (3,2,1,5,6,4), which are:
1→3→1 (2 steps);
2→2 (1 steps);
3→1→3 (2 steps);
4→5→6→4 (3 steps);
5→6→4→5 (3 steps);
6→4→5→6 (3 steps);
So how many times to rearrange the whole sequence to return to the original order, is obviously the LCM (2,1,2,3,3,3) = 6, that is, each bit back to the origin of the minimum number of steps least common multiple;
AC Code:
1#include <cstdio>2 intn,p[ the],ans=1;3 intgcdintMintN) {returnN?GCD (n,m%N): M;}4 intLcmintMintN) {returnM/GCD (m,n) *N;}5 intMain ()6 {7scanf"%d",&n);8 for(intI=1; i<=n;i++) scanf ("%d",&p[i]);9 for(intI=1; i<=n;i++)Ten { One intNow=p[i],cnt=1; A while(1) - { - if(now==i) Break; the Else - { -now=P[now]; -cnt++; + } - } +ans=LCM (ans,cnt); A } atprintf"%d\n", ans); -}
PS. Although using GCD, but I am embarrassed to put the number theory classification, put other categories in it ...
Hihocoder 1330-Array rearrangement-[Hiho for 167 weeks] [least common multiple]