#include <iostream> #include <vector> #include <algorithm> #include <deque> #define ALL(v) begin(v), end(v) using namespace std; int main() { ios_base::sync_with_stdio(0); int n; cin >> n; vector<int> V(n); for(auto &v:V) cin>>v; if(is_sorted(ALL(V))) { cout << "0\n"; return 0; } auto T = V; sort(ALL(V)); for(auto &v:T) v = lower_bound(ALL(V),v) - V.begin(); vector<bool> vis(n, false); vector<vector<int>> cycles; for(int i=0;i<n;i++) if(!vis[i]) { int cur = i; vis[i] = true; vector<int> C; C.push_back(i); while(!vis[T[cur]]) { cur = T[cur]; C.push_back(cur); vis[cur] = true; } cycles.push_back(move(C)); } deque<int> res; for(auto &C:cycles) if(C.size() > 1) { if(C.size() == 2) { res.push_front(C[0]); res.push_back(C[1]); swap(T[C[0]],T[C[1]]); continue; } for(int p=0,k=C.size()-2;p<k;p++,k--) { res.push_front(C[p]); res.push_back(C[k]); swap(T[C[p]],T[C[k]]); } } auto ret_res = [&res] { cout << res.size() << '\n'; for(auto v:res) cout << v + 1 << ' '; cout << '\n'; }; if(is_sorted(ALL(T))) { cout << "1\n"; ret_res(); return 0; } cout << "2\n"; ret_res(); res.clear(); for(auto &C:cycles) if(C.size() > 2) { for(int p=0,k=C.size()-1;p<k;p++,k--) { res.push_front(C[p]); res.push_back(C[k]); } } ret_res(); 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 68 69 70 71 | #include <iostream> #include <vector> #include <algorithm> #include <deque> #define ALL(v) begin(v), end(v) using namespace std; int main() { ios_base::sync_with_stdio(0); int n; cin >> n; vector<int> V(n); for(auto &v:V) cin>>v; if(is_sorted(ALL(V))) { cout << "0\n"; return 0; } auto T = V; sort(ALL(V)); for(auto &v:T) v = lower_bound(ALL(V),v) - V.begin(); vector<bool> vis(n, false); vector<vector<int>> cycles; for(int i=0;i<n;i++) if(!vis[i]) { int cur = i; vis[i] = true; vector<int> C; C.push_back(i); while(!vis[T[cur]]) { cur = T[cur]; C.push_back(cur); vis[cur] = true; } cycles.push_back(move(C)); } deque<int> res; for(auto &C:cycles) if(C.size() > 1) { if(C.size() == 2) { res.push_front(C[0]); res.push_back(C[1]); swap(T[C[0]],T[C[1]]); continue; } for(int p=0,k=C.size()-2;p<k;p++,k--) { res.push_front(C[p]); res.push_back(C[k]); swap(T[C[p]],T[C[k]]); } } auto ret_res = [&res] { cout << res.size() << '\n'; for(auto v:res) cout << v + 1 << ' '; cout << '\n'; }; if(is_sorted(ALL(T))) { cout << "1\n"; ret_res(); return 0; } cout << "2\n"; ret_res(); res.clear(); for(auto &C:cycles) if(C.size() > 2) { for(int p=0,k=C.size()-1;p<k;p++,k--) { res.push_front(C[p]); res.push_back(C[k]); } } ret_res(); return 0; } |