#include<cstdio> #include<algorithm> using namespace std; const int N=3005; int n,i,j,k,a[N],b[N],ans,now,left[N],right[N],op[N][N],cnt,q[N],vis[N]; int main(){ scanf("%d",&n); for(i=1;i<=n;i++){ scanf("%d",&a[i]); //a[i]=i+1; //if(i==n)a[i]=1; b[i]=a[i]; } sort(b+1,b+n+1); for(i=1;i<=n;i++)a[i]=lower_bound(b+1,b+n+1,a[i])-b; while(1){ //for(i=1;i<=n;i++)printf("%d%c",a[i],i<n?' ':'\n'); now=0; for(i=1;i<=n;i++)vis[i]=0; for(i=1;i<=n;i++)if(!vis[i]){ cnt=0; for(j=i;!vis[j];j=a[j]){ vis[j]=1; q[++cnt]=j; } if(cnt==1)continue; for(j=1,k=cnt;j<k;j++,k--){ left[++now]=q[j]; right[now]=q[k]; } } if(!now)break; ans++; op[ans][0]=now*2; for(i=1;i<=now;i++){ op[ans][i]=left[i]; op[ans][now*2-i+1]=right[i]; //printf("swap %d %d\n",left[i],right[i]); swap(a[left[i]],a[right[i]]); } } printf("%d\n",ans); for(i=1;i<=ans;i++){ now=op[i][0]; printf("%d\n",now); for(j=1;j<=now;j++)printf("%d%c",op[i][j],j<now?' ':'\n'); } //for(i=1;i<=n;i++)printf("%d ",a[i]); }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | #include<cstdio> #include<algorithm> using namespace std; const int N=3005; int n,i,j,k,a[N],b[N],ans,now,left[N],right[N],op[N][N],cnt,q[N],vis[N]; int main(){ scanf("%d",&n); for(i=1;i<=n;i++){ scanf("%d",&a[i]); //a[i]=i+1; //if(i==n)a[i]=1; b[i]=a[i]; } sort(b+1,b+n+1); for(i=1;i<=n;i++)a[i]=lower_bound(b+1,b+n+1,a[i])-b; while(1){ //for(i=1;i<=n;i++)printf("%d%c",a[i],i<n?' ':'\n'); now=0; for(i=1;i<=n;i++)vis[i]=0; for(i=1;i<=n;i++)if(!vis[i]){ cnt=0; for(j=i;!vis[j];j=a[j]){ vis[j]=1; q[++cnt]=j; } if(cnt==1)continue; for(j=1,k=cnt;j<k;j++,k--){ left[++now]=q[j]; right[now]=q[k]; } } if(!now)break; ans++; op[ans][0]=now*2; for(i=1;i<=now;i++){ op[ans][i]=left[i]; op[ans][now*2-i+1]=right[i]; //printf("swap %d %d\n",left[i],right[i]); swap(a[left[i]],a[right[i]]); } } printf("%d\n",ans); for(i=1;i<=ans;i++){ now=op[i][0]; printf("%d\n",now); for(j=1;j<=now;j++)printf("%d%c",op[i][j],j<now?' ':'\n'); } //for(i=1;i<=n;i++)printf("%d ",a[i]); } |