#include <algorithm>
#include <cstdio>
#include <vector>
#include <set>
using namespace std;
long a[3001];
long ab[3001];
long as[3001];
long ad[3001];
void reverse(long i, long dest, vector<long>& resi)
{
ab[i] = 1;
ab[dest] = 1;
resi.insert(resi.begin(), i);
resi.push_back(dest);
ad[a[i]] = dest;
ad[a[dest]] = i;
long tmp = a[i];
a[i] = a[dest];
a[dest] = tmp;
if (a[i] != i && a[i] != ad[i] && ab[a[i]] == 0 && ab[ad[i]] == 0)
{
reverse(ad[i], a[i], resi);
}
}
int main()
{
long n, hi;
scanf("%ld", &n);
for (long i = 0; i < 3001; ++i)
as[i] = -1;
for (long i = 0; i < n; ++i)
{
scanf("%ld", &hi);
as[hi] = i;
}
long ii = 0;
for (long i = 0; i < 3001; ++i)
if (as[i] >= 0)
{
ad[ii] = as[i];
a[as[i]] = ii++;
}
vector<vector<long> > res;
while (true)
{
long l = 0;
for (long i = 0; i < n; ++i)
{
if (a[i] != i)
{
ab[i] = 0;
++l;
}
else
ab[i] = 1;
}
if (l == 0)
{
printf("%d", res.size());
for (int i = 0; i < res.size(); ++i)
{
printf("\n%d\n", res[i].size());
for (int j = 0; j < res[i].size(); ++j)
printf("%ld ", res[i][j] + 1);
}
return 0;
}
vector<long> resi;
for (long i = 0; i < n; ++i)
{
if (ab[i] == 0)
{
long dest = a[i];
if (ab[dest] == 1 && a[dest] != i)
dest = a[dest];
if (ab[dest] == 0)
{
reverse(i, dest, resi);
}
}
}
res.push_back(resi);
}
printf("%s\n", "NIE");
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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | #include <algorithm> #include <cstdio> #include <vector> #include <set> using namespace std; long a[3001]; long ab[3001]; long as[3001]; long ad[3001]; void reverse(long i, long dest, vector<long>& resi) { ab[i] = 1; ab[dest] = 1; resi.insert(resi.begin(), i); resi.push_back(dest); ad[a[i]] = dest; ad[a[dest]] = i; long tmp = a[i]; a[i] = a[dest]; a[dest] = tmp; if (a[i] != i && a[i] != ad[i] && ab[a[i]] == 0 && ab[ad[i]] == 0) { reverse(ad[i], a[i], resi); } } int main() { long n, hi; scanf("%ld", &n); for (long i = 0; i < 3001; ++i) as[i] = -1; for (long i = 0; i < n; ++i) { scanf("%ld", &hi); as[hi] = i; } long ii = 0; for (long i = 0; i < 3001; ++i) if (as[i] >= 0) { ad[ii] = as[i]; a[as[i]] = ii++; } vector<vector<long> > res; while (true) { long l = 0; for (long i = 0; i < n; ++i) { if (a[i] != i) { ab[i] = 0; ++l; } else ab[i] = 1; } if (l == 0) { printf("%d", res.size()); for (int i = 0; i < res.size(); ++i) { printf("\n%d\n", res[i].size()); for (int j = 0; j < res[i].size(); ++j) printf("%ld ", res[i][j] + 1); } return 0; } vector<long> resi; for (long i = 0; i < n; ++i) { if (ab[i] == 0) { long dest = a[i]; if (ab[dest] == 1 && a[dest] != i) dest = a[dest]; if (ab[dest] == 0) { reverse(i, dest, resi); } } } res.push_back(resi); } printf("%s\n", "NIE"); return 0; } |
English