First, the last number of times I was placed in the I position is the least: feel, can, with inductive method?
By adding an identical sequence after the sequence, you can simulate a situation that starts with each number.
Each position is not correct, only need to change once
54123, 5 fixed->41235 becomes 12345
Any number is fixed, which is equivalent to the position of the corresponding 1 from the beginning of the row 12345. (For example 54123, 5 fixed->41235 to 12345) so only need to start each position to determine the number of steps to 12345 required
Turn the input upside down and turn it into 12345 equals 54321 (this symmetry is ingenious), can be modular
#include <cstdio>#include<algorithm>using namespacestd;intCalintA[],intN) {//54123->12345 can be seen as 12354->12345 so each position begins to be judged as 12345 required steps intCNT =0, vis[505] = {0}; for(inti =1; I <= N; i++)//CNT statistics do not need to change the number of positions; no transposition of the a[j] is equal to J, into the next number if(!vis[i]) {//a number is not in the right place .cnt++; for(intj = i;!vis[j]; j = A[j])//the loop keeps changing until you don't have to change.VIS[J] =1; } returnNCNT;}intMain () {intN, a[1010], b[1010]; while(SCANF ("%d", &N), N) { for(inti =1; I <= N; i++) {scanf ("%d", &A[i]); B[n-i +1] = b[2* N-i +1] = A[i + N] =A[i]; } intAns =1<< -; for(inti =0; i < N; i++) ans= min (ans, cal (A +I, N)); for(inti =0; i < N; i++) ans= min (ans, cal (B +I, N)); printf ("%d\n", ans); } return 0;} #include<cstdio>#include<cstring>#include<algorithm>using namespacestd;Const intN =505;intP[n],k[n],w[n];intF[n],n;intSolveintSintd) {intCNT =0; for(inti =1; I <= N; i++) { if(K[i]! =s) {cnt++; K[w[s]]=K[i]; W[k[i]]=W[s]; K[i]=s; W[s]=i; } s+=D; if(S >N) S=1; if(S <=0) s=N; } returnCNT;}intMain () { while(SCANF ("%d", &n) &&N) { for(inti =1; I <= N; i++) {scanf ("%d",&P[i]); F[p[i]]=i; } intMin =0x3f3f3f3f; for(inti =1; I <= N; i++) {memcpy (k, p,sizeof(p)); memcpy (W, F,sizeof(f)); Min= min (min, Solve (i,-1)); memcpy (k, p,sizeof(p)); memcpy (W, F,sizeof(f)); Min= min (min, Solve (i,1)); } printf ("%d\n", Min); }}
UVA10570 meeting with aliens