#include <algorithm> #include <iostream> #include <map> #include <vector> using namespace std; const int nMax = 3005; vector<int> res[20]; int h[nMax]; int temp[nMax]; bool swapped[nMax]; int n; map<int, int> mp; bool isOk = false; bool check() { for(int i=1;i<=n;i++) { if(h[i] != i) return false; } return true; } void myFill(bool arr[]) { for(int i=1;i<=n;i++) arr[i] = false; } void read() { cin>>n; for(int i=1;i<=n;i++) { cin>>h[i]; temp[i] = h[i]; } sort(temp+1,temp+1+n); int cnt = 1; for(int i=1;i<=n;i++) { mp[temp[i]] = cnt++; } for(int i=1;i<=n;i++) h[i] = mp[h[i]]; } void display() { for(int i=1;i<=n;i++) cout<<"h["<<i<<"] = "<<h[i]<<"\n"; } int main() { read(); //display(); int cnt = 0; isOk = check(); while(isOk == false){ myFill(swapped); for(int i=1;i<=n;i++) { if(swapped[i] == false && swapped[h[i]] == false && h[i] != i) { res[cnt].push_back(i); res[cnt].push_back(h[i]); //cout<<"swapping: index: "<<i<<" and "<<h[i]<<"\n"; swapped[h[i]] = true; swapped[i] = true; swap(h[i], h[h[i]]); } } isOk = check(); cnt++; //cout<<cnt<<"\n"; //display(); } cout<<cnt<<"\n"; for(int i=0;i<cnt;i++) { cout<<res[i].size()<<"\n"; for(int j=0;j<res[i].size()/2;j++) cout<<res[i][j*2]<<" "; for(int j=0;j<res[i].size()/2;j++) cout<<res[i][res[i].size()-1-2*j]<<" "; cout<<"\n"; } }
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | #include <algorithm> #include <iostream> #include <map> #include <vector> using namespace std; const int nMax = 3005; vector<int> res[20]; int h[nMax]; int temp[nMax]; bool swapped[nMax]; int n; map<int, int> mp; bool isOk = false; bool check() { for(int i=1;i<=n;i++) { if(h[i] != i) return false; } return true; } void myFill(bool arr[]) { for(int i=1;i<=n;i++) arr[i] = false; } void read() { cin>>n; for(int i=1;i<=n;i++) { cin>>h[i]; temp[i] = h[i]; } sort(temp+1,temp+1+n); int cnt = 1; for(int i=1;i<=n;i++) { mp[temp[i]] = cnt++; } for(int i=1;i<=n;i++) h[i] = mp[h[i]]; } void display() { for(int i=1;i<=n;i++) cout<<"h["<<i<<"] = "<<h[i]<<"\n"; } int main() { read(); //display(); int cnt = 0; isOk = check(); while(isOk == false){ myFill(swapped); for(int i=1;i<=n;i++) { if(swapped[i] == false && swapped[h[i]] == false && h[i] != i) { res[cnt].push_back(i); res[cnt].push_back(h[i]); //cout<<"swapping: index: "<<i<<" and "<<h[i]<<"\n"; swapped[h[i]] = true; swapped[i] = true; swap(h[i], h[h[i]]); } } isOk = check(); cnt++; //cout<<cnt<<"\n"; //display(); } cout<<cnt<<"\n"; for(int i=0;i<cnt;i++) { cout<<res[i].size()<<"\n"; for(int j=0;j<res[i].size()/2;j++) cout<<res[i][j*2]<<" "; for(int j=0;j<res[i].size()/2;j++) cout<<res[i][res[i].size()-1-2*j]<<" "; cout<<"\n"; } } |