#include <iostream> #include <unordered_map> #include <functional> #include <algorithm> #include <vector> #include <deque> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; vector<int> V(n); for (auto& v : V) cin >> v; vector<int> S = V; sort(S.begin(), S.end()); unordered_map<int, int> P(n); for (int i = 0; i < n; i++) P[S[i]] = i; vector<deque<int>> R; while (true) { if (is_sorted(V.begin(), V.end())) { cout << R.size() << '\n'; for (auto& r : R) { cout << r.size() << '\n'; for (auto& q : r) cout << q + 1 << ' '; cout << '\n'; } break; } vector<int> C; vector<bool> vis(n); function<void(int)> DFS = [&](int u) { if (vis[u]) return; vis[u] = true; C.push_back(u); DFS(P[V[u]]); }; deque<int> Q; for (int i = 0; i < n; i++) { C.resize(0); if (!vis[i]) { DFS(i); for (int i = 0; i < C.size() / 2; i++) Q.push_front(C[i]), Q.push_back(C[C.size() - i - 1]); } } R.push_back(Q); while (Q.size()) { swap(V[Q.front()], V[Q.back()]); Q.pop_back(), Q.pop_front(); } } }
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 <iostream> #include <unordered_map> #include <functional> #include <algorithm> #include <vector> #include <deque> using namespace std; int main() { ios::sync_with_stdio(0); cin.tie(0); int n; cin >> n; vector<int> V(n); for (auto& v : V) cin >> v; vector<int> S = V; sort(S.begin(), S.end()); unordered_map<int, int> P(n); for (int i = 0; i < n; i++) P[S[i]] = i; vector<deque<int>> R; while (true) { if (is_sorted(V.begin(), V.end())) { cout << R.size() << '\n'; for (auto& r : R) { cout << r.size() << '\n'; for (auto& q : r) cout << q + 1 << ' '; cout << '\n'; } break; } vector<int> C; vector<bool> vis(n); function<void(int)> DFS = [&](int u) { if (vis[u]) return; vis[u] = true; C.push_back(u); DFS(P[V[u]]); }; deque<int> Q; for (int i = 0; i < n; i++) { C.resize(0); if (!vis[i]) { DFS(i); for (int i = 0; i < C.size() / 2; i++) Q.push_front(C[i]), Q.push_back(C[C.size() - i - 1]); } } R.push_back(Q); while (Q.size()) { swap(V[Q.front()], V[Q.back()]); Q.pop_back(), Q.pop_front(); } } } |