A 1-N arrangement can exchange two numbers. Each round can be exchanged multiple times, but each number can only be exchanged once, you can change the order from 1, 2, 3 ..., n Arrangement
Idea: Find out all the cycle sections. The cycle section with a length of 2 only needs to be performed once, and the remaining section requires two times.
Proof: the circular section with a length of 2 is obviously exchanged only once, and the rest can be pulled into a chain (arranged with 1, 2, 3 ,..., n). If this chain is switched from two ends to the center in sequence (I .e., I and k + 1-i), the original crossover chain will be broken, that is to say, the loop section is broken down, and the cross chain is up to 2, so it only needs to be OK twice.
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; int A[5010]; int F[5010]; int t[5010]; int vis[5010]; int ct,ans,d[5010][2]; int dfs(int x) { t[++ct]=A[x]; if(!vis[A[x]]) { vis[A[x]]=1; dfs(A[x]); } } int check(int n) { for(int i=1; i<=n; i++) { if(i!=A[i])return 0; } return 1; } int solve(int n) { int f=0; memset(vis,0,sizeof(vis)); for(int i=1; i<=n; i++) { if(!vis[i]) { ct=0; vis[i]=1; dfs(i); if(ct>2)f=1; if(ct>=2) { for(int j=1; j<=ct/2; j++) { d[ans][0]=t[j]; d[ans][1]=t[ct+1-j]; ans++; swap(A[F[t[j]]],A[F[t[ct+1-j]]]); swap(F[t[j]],F[t[ct+1-j]]); } } } } if(!f) return 0; else return 1; } int main() { int n,f=0; scanf("%d",&n); for(int i=1; i<=n; i++) { scanf("%d",&A[i]); F[A[i]]=i; } ans=0; if(check(n)) { printf("0\n"); } else { if(!solve(n)) { printf("1\n%d",ans); for(int i=0;i<ans;i++) printf(" %d-%d",d[i][0],d[i][1]); printf("\n"); } else { printf("2\n%d",ans); for(int i=0;i<ans;i++) printf(" %d-%d",d[i][0],d[i][1]); printf("\n"); ans=0; solve(n); printf("%d",ans); for(int i=0;i<ans;i++) printf(" %d-%d",d[i][0],d[i][1]); printf("\n"); } } return 0; } #include <stdio.h>#include <string.h>#include <algorithm>using namespace std;int A[5010];int F[5010];int t[5010];int vis[5010];int ct,ans,d[5010][2];int dfs(int x){ t[++ct]=A[x]; if(!vis[A[x]]) { vis[A[x]]=1; dfs(A[x]); }}int check(int n){ for(int i=1; i<=n; i++) { if(i!=A[i])return 0; } return 1;}int solve(int n){ int f=0; memset(vis,0,sizeof(vis)); for(int i=1; i<=n; i++) { if(!vis[i]) { ct=0; vis[i]=1; dfs(i); if(ct>2)f=1; if(ct>=2) { for(int j=1; j<=ct/2; j++) { d[ans][0]=t[j]; d[ans][1]=t[ct+1-j]; ans++; swap(A[F[t[j]]],A[F[t[ct+1-j]]]); swap(F[t[j]],F[t[ct+1-j]]); } } } } if(!f) return 0; else return 1;}int main(){ int n,f=0; scanf("%d",&n); for(int i=1; i<=n; i++) { scanf("%d",&A[i]); F[A[i]]=i; } ans=0; if(check(n)) { printf("0\n"); } else { if(!solve(n)) { printf("1\n%d",ans); for(int i=0;i<ans;i++) printf(" %d-%d",d[i][0],d[i][1]); printf("\n"); } else { printf("2\n%d",ans); for(int i=0;i<ans;i++) printf(" %d-%d",d[i][0],d[i][1]); printf("\n"); ans=0; solve(n); printf("%d",ans); for(int i=0;i<ans;i++) printf(" %d-%d",d[i][0],d[i][1]); printf("\n"); } } return 0;}