#include <bits/stdc++.h> using namespace std; const int MX=3030; int n,i,j,k,cnt,a[MX],b[MX]; vector<vector<int>> res; bool u[MX]; int main() { scanf("%d",&n); for (i=0; i<n; i++) { scanf("%d",&a[i]); b[i]=a[i]; } sort(b,b+n); for (i=0; i<n; i++) a[i]=lower_bound(b,b+n,a[i])-b; while (true) { vector<int> v,e; for (i=0; i<n; i++) u[i]=false; for (i=0; i<n; i++) if (a[i]!=i && !u[i]) { vector<int> c; for (j=i; !u[j]; j=a[j]) { c.push_back(j); u[j]=true; } k=int(c.size())-1; if (k>2) { for (j=1; j<k; j++, k--) { v.push_back(c[j]); e.push_back(c[k]); } } else { v.push_back(c[0]); e.push_back(c[1]); } } cnt=v.size(); if (cnt==0) break; res.push_back(v); for (i=0; i<cnt; i++) { swap(a[v[i]],a[e[i]]); res.back().push_back(e[cnt-i-1]); } } printf("%d\n",int(res.size())); for (const auto& v: res) { printf("%d\n",int(v.size())); for (int x: v) printf("%d ",x+1); puts(""); } return 0; }
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 50 | #include <bits/stdc++.h> using namespace std; const int MX=3030; int n,i,j,k,cnt,a[MX],b[MX]; vector<vector<int>> res; bool u[MX]; int main() { scanf("%d",&n); for (i=0; i<n; i++) { scanf("%d",&a[i]); b[i]=a[i]; } sort(b,b+n); for (i=0; i<n; i++) a[i]=lower_bound(b,b+n,a[i])-b; while (true) { vector<int> v,e; for (i=0; i<n; i++) u[i]=false; for (i=0; i<n; i++) if (a[i]!=i && !u[i]) { vector<int> c; for (j=i; !u[j]; j=a[j]) { c.push_back(j); u[j]=true; } k=int(c.size())-1; if (k>2) { for (j=1; j<k; j++, k--) { v.push_back(c[j]); e.push_back(c[k]); } } else { v.push_back(c[0]); e.push_back(c[1]); } } cnt=v.size(); if (cnt==0) break; res.push_back(v); for (i=0; i<cnt; i++) { swap(a[v[i]],a[e[i]]); res.back().push_back(e[cnt-i-1]); } } printf("%d\n",int(res.size())); for (const auto& v: res) { printf("%d\n",int(v.size())); for (int x: v) printf("%d ",x+1); puts(""); } return 0; } |