#include <bits/stdc++.h> using namespace std; const int N = 3000 + 9; int n; int v[N]; void rescale() { int used[N]; for (int i=0; i<N; ++i) used[i] = -2; for (int i=0; i<n; ++i) used[v[i]] = -1; int next = -1; for (int i=0; i<N; ++i) if (used[i] == -1) used[i] = ++next; for (int i=0; i<n; ++i) v[i] = used[v[i]]; } void fillStep(deque<int> &q) { int done[N]; for (int i=0; i<n; ++i) done[i] = 0; for (int i=0; i<n; ++i) if (0 == done[i]) { vector<int> cycle; int start = i; cycle.push_back(i); done[i] = 1; for (int j=v[i]; j!=start; j=v[j]) { done[j] = 1; cycle.push_back(j); } int a = 0; int b = cycle.size() - 1; while (a < b) { q.push_front(cycle[a]); q.push_back(cycle[b]); swap(v[cycle[a]], v[cycle[b]]); ++a; --b; } } } void printStep(deque<int> &q) { if (q.empty()) return; printf("%d\n", (int)q.size()); for (int i=0; i<q.size(); ++i) printf("%d%s", q[i] + 1, i+1<q.size() ? " " : "\n"); } void solve() { deque<int> step1; fillStep(step1); deque<int> step2; fillStep(step2); int cnt = 0; if (!step1.empty()) ++cnt; if (!step2.empty()) ++cnt; printf("%d\n", cnt); printStep(step1); printStep(step2); } int main() { scanf("%d", &n); for (int i=0; i<n; ++i) scanf("%d", v + i); rescale(); solve(); 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 <bits/stdc++.h> using namespace std; const int N = 3000 + 9; int n; int v[N]; void rescale() { int used[N]; for (int i=0; i<N; ++i) used[i] = -2; for (int i=0; i<n; ++i) used[v[i]] = -1; int next = -1; for (int i=0; i<N; ++i) if (used[i] == -1) used[i] = ++next; for (int i=0; i<n; ++i) v[i] = used[v[i]]; } void fillStep(deque<int> &q) { int done[N]; for (int i=0; i<n; ++i) done[i] = 0; for (int i=0; i<n; ++i) if (0 == done[i]) { vector<int> cycle; int start = i; cycle.push_back(i); done[i] = 1; for (int j=v[i]; j!=start; j=v[j]) { done[j] = 1; cycle.push_back(j); } int a = 0; int b = cycle.size() - 1; while (a < b) { q.push_front(cycle[a]); q.push_back(cycle[b]); swap(v[cycle[a]], v[cycle[b]]); ++a; --b; } } } void printStep(deque<int> &q) { if (q.empty()) return; printf("%d\n", (int)q.size()); for (int i=0; i<q.size(); ++i) printf("%d%s", q[i] + 1, i+1<q.size() ? " " : "\n"); } void solve() { deque<int> step1; fillStep(step1); deque<int> step2; fillStep(step2); int cnt = 0; if (!step1.empty()) ++cnt; if (!step2.empty()) ++cnt; printf("%d\n", cnt); printStep(step1); printStep(step2); } int main() { scanf("%d", &n); for (int i=0; i<n; ++i) scanf("%d", v + i); rescale(); solve(); return 0; } |