#include <bits/stdc++.h> using namespace std; int tab[3005]; int sorted[3005]; int nr2targetPos[3005]; bool added[3005]; vector<vector<int>> vectors; int main() { int n; cin >> n; for(int i=0;i<n;i++) { cin >> tab[i]; sorted[i] = tab[i]; } sort(sorted, sorted + n); for(int i=0;i<n;i++) { nr2targetPos[sorted[i]] = i; } while(true) { for(int i=0;i<=3001;i++) { added[i] = false; } bool ok = true; vector<int> v; for(int i=0;i<n;i++) { int nr = tab[i]; int pos = i; int targetpos = nr2targetPos[nr]; if(pos == targetpos) { continue; } ok = false; if(!added[pos] && !added[targetpos]) { added[pos] = true; added[targetpos] = true; v.push_back(pos); v.push_back(targetpos); int tmp = tab[pos]; tab[pos] = tab[targetpos]; tab[targetpos] = tmp; } } if(ok) { break; } vectors.push_back(v); } cout << vectors.size() << "\n"; for(int i=0; i<vectors.size(); i++) { vector<int> v = vectors[i]; cout << v.size() << "\n"; for(int j=0; j<v.size(); j++) { if(j%2==0) { cout << (v[j]+1) << " "; } } for(int j=v.size()-1; j>=0; j--) { if(j%2==1) { cout << (v[j]+1) << " "; } } cout << "\n"; } 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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | #include <bits/stdc++.h> using namespace std; int tab[3005]; int sorted[3005]; int nr2targetPos[3005]; bool added[3005]; vector<vector<int>> vectors; int main() { int n; cin >> n; for(int i=0;i<n;i++) { cin >> tab[i]; sorted[i] = tab[i]; } sort(sorted, sorted + n); for(int i=0;i<n;i++) { nr2targetPos[sorted[i]] = i; } while(true) { for(int i=0;i<=3001;i++) { added[i] = false; } bool ok = true; vector<int> v; for(int i=0;i<n;i++) { int nr = tab[i]; int pos = i; int targetpos = nr2targetPos[nr]; if(pos == targetpos) { continue; } ok = false; if(!added[pos] && !added[targetpos]) { added[pos] = true; added[targetpos] = true; v.push_back(pos); v.push_back(targetpos); int tmp = tab[pos]; tab[pos] = tab[targetpos]; tab[targetpos] = tmp; } } if(ok) { break; } vectors.push_back(v); } cout << vectors.size() << "\n"; for(int i=0; i<vectors.size(); i++) { vector<int> v = vectors[i]; cout << v.size() << "\n"; for(int j=0; j<v.size(); j++) { if(j%2==0) { cout << (v[j]+1) << " "; } } for(int j=v.size()-1; j>=0; j--) { if(j%2==1) { cout << (v[j]+1) << " "; } } cout << "\n"; } return 0; } |