#include <bits/stdc++.h> using namespace std; bool sorted(vector<int> &v){ for(int i = 0; i < v.size() - 1; i++){ if(v[i] > v[i + 1]){ return false; } } return true; } int main(){ int n; cin >> n; //cout << n << endl; vector<int> h(n), pos(n, 0); for(int i = 0; i < n; i++){ cin >> h[i]; //cout << h[i] << ' '; } //cout << endl; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(h[j] < h[i]){ pos[i]++; } } } vector<vector<int>> answer; while(!sorted(h)){ vector<vector<int>> cycles; vector<bool> processed(n, false); for(int i = 0; i < n; i++){ if(processed[i]) continue; if(pos[i] == i) continue; int akt = pos[i]; cycles.push_back({i}); while(akt != i){ cycles.back().push_back(akt); processed[akt] = true; akt = pos[akt]; } } deque<int> d; for(auto cycle : cycles){ for(int i = 0; i < cycle.size() / 2; i++){ d.push_front(cycle[i]); d.push_back(cycle[cycle.size() - 1 - i]); swap(h[cycle[i]], h[cycle[cycle.size() - 1 - i]]); swap(pos[cycle[i]], pos[cycle[cycle.size() - 1 - i]]); } } answer.push_back({d.begin(), d.end()}); } cout << answer.size() << '\n'; for(auto row : answer){ cout << row.size() << '\n'; for(auto el : row){ cout << el + 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 | #include <bits/stdc++.h> using namespace std; bool sorted(vector<int> &v){ for(int i = 0; i < v.size() - 1; i++){ if(v[i] > v[i + 1]){ return false; } } return true; } int main(){ int n; cin >> n; //cout << n << endl; vector<int> h(n), pos(n, 0); for(int i = 0; i < n; i++){ cin >> h[i]; //cout << h[i] << ' '; } //cout << endl; for(int i = 0; i < n; i++){ for(int j = 0; j < n; j++){ if(h[j] < h[i]){ pos[i]++; } } } vector<vector<int>> answer; while(!sorted(h)){ vector<vector<int>> cycles; vector<bool> processed(n, false); for(int i = 0; i < n; i++){ if(processed[i]) continue; if(pos[i] == i) continue; int akt = pos[i]; cycles.push_back({i}); while(akt != i){ cycles.back().push_back(akt); processed[akt] = true; akt = pos[akt]; } } deque<int> d; for(auto cycle : cycles){ for(int i = 0; i < cycle.size() / 2; i++){ d.push_front(cycle[i]); d.push_back(cycle[cycle.size() - 1 - i]); swap(h[cycle[i]], h[cycle[cycle.size() - 1 - i]]); swap(pos[cycle[i]], pos[cycle[cycle.size() - 1 - i]]); } } answer.push_back({d.begin(), d.end()}); } cout << answer.size() << '\n'; for(auto row : answer){ cout << row.size() << '\n'; for(auto el : row){ cout << el + 1 << ' '; } cout << '\n'; } return 0; } |