#include <cstdio>
#include <algorithm>
#include <vector>
#include <deque>
#define scanf(...) scanf(__VA_ARGS__)?:0
using namespace std;
int n, a[3001], c[3001];
pair<int, int> b[3001];
int odw[3001];
vector<int> v[3001];
deque<int> d1, d2;
int main() {
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
b[i] = {a[i], i};
}
sort(b+1, b+n+1);
for (int i = 1; i <= n; i++) c[b[i].second] = i;
int cykle = 0;
for (int i = 1; i <= n; i++) {
if (odw[i]) continue;
int x = i;
odw[x] = 1;
v[cykle].push_back(x);
x = c[x];
while (x != i) {
v[cykle].push_back(x);
odw[x] = 1;
x = c[x];
}
cykle++;
}
for (int i = 0; i < cykle; i++) {
if (v[i].size() == 1) continue;
if (v[i].size() == 2) {
d1.push_front(v[i][0]);
d1.push_back(v[i][1]);
} else {
int p = 0, k = v[i].size() - 2;
while (p < k) {
d1.push_front(v[i][p++]);
d1.push_back(v[i][k--]);
}
p = 0; k = v[i].size() - 1;
while (p < k) {
d2.push_front(v[i][p++]);
d2.push_back(v[i][k--]);
}
}
}
if (d1.empty()) puts("0");
else if (d2.empty()) {
puts("1");
printf("%lu\n", d1.size());
for (int x: d1) printf("%d ", x);
puts("");
} else {
puts("2");
printf("%lu\n", d1.size());
for (int x: d1) printf("%d ", x);
puts("");
printf("%lu\n", d2.size());
for (int x: d2) printf("%d ", x);
puts("");
}
}
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 72 73 74 | #include <cstdio> #include <algorithm> #include <vector> #include <deque> #define scanf(...) scanf(__VA_ARGS__)?:0 using namespace std; int n, a[3001], c[3001]; pair<int, int> b[3001]; int odw[3001]; vector<int> v[3001]; deque<int> d1, d2; int main() { scanf("%d", &n); for (int i = 1; i <= n; i++) { scanf("%d", &a[i]); b[i] = {a[i], i}; } sort(b+1, b+n+1); for (int i = 1; i <= n; i++) c[b[i].second] = i; int cykle = 0; for (int i = 1; i <= n; i++) { if (odw[i]) continue; int x = i; odw[x] = 1; v[cykle].push_back(x); x = c[x]; while (x != i) { v[cykle].push_back(x); odw[x] = 1; x = c[x]; } cykle++; } for (int i = 0; i < cykle; i++) { if (v[i].size() == 1) continue; if (v[i].size() == 2) { d1.push_front(v[i][0]); d1.push_back(v[i][1]); } else { int p = 0, k = v[i].size() - 2; while (p < k) { d1.push_front(v[i][p++]); d1.push_back(v[i][k--]); } p = 0; k = v[i].size() - 1; while (p < k) { d2.push_front(v[i][p++]); d2.push_back(v[i][k--]); } } } if (d1.empty()) puts("0"); else if (d2.empty()) { puts("1"); printf("%lu\n", d1.size()); for (int x: d1) printf("%d ", x); puts(""); } else { puts("2"); printf("%lu\n", d1.size()); for (int x: d1) printf("%d ", x); puts(""); printf("%lu\n", d2.size()); for (int x: d2) printf("%d ", x); puts(""); } } |
English