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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
#include <cstdio>
#include <vector>
#include <algorithm>

using namespace std;

const int MAX_N = 3007;

int n;
int h[MAX_N];
int pos[MAX_N];
bool vis[MAX_N];

void scale() {
    int j = 1;

    for (int i = 1; i <= n; i++)
        pos[h[i]] = i;

    for (int i = 1; i < MAX_N; i++)
        if (pos[i] > 0)
            h[pos[i]] = j++;
}

int longest_cycle() {
    int lc = 0;
    fill(&vis[1], &vis[n + 1], false);

    for (int i = 1; i <= n; i++) {
        int c = 0;
        int j = i;

        while (!vis[j]) {
            vis[j] = true;
            c++;
            j = h[j];
        }

        lc = max(c, lc);
    }

    return lc;
}

void print_round(vector<int>& p, vector<int>& q) {
    printf("%lu\n", p.size() + q.size());

    for (int e : p)
        printf("%d ", e);

    for (int i = q.size() - 1; i >= 0; i--)
        printf("%d ", q[i]);

    printf("\n");
}

void solve2() {
    vector<int> p, q;
    fill(&vis[1], &vis[n + 1], false);

    for (int i = 1; i <= n; i++) {
        if (h[i] != i && !vis[i]) {
            p.push_back(i);
            q.push_back(h[i]);
            vis[i] = vis[h[i]] = true;
            swap(h[i], h[h[i]]);
        }
    }

    print_round(p, q);
}

void split_cycle(vector<int>& pos, vector<int>& p, vector<int>& q) {
    if (pos.size() <= 2) {
        return;
    }

    int i = 0;
    int j = pos.size() - 1;

    while (i < j - 1) {
        p.push_back(pos[i]);
        q.push_back(pos[j - 1]);
        swap(h[pos[i]], h[pos[j - 1]]);
        i++;
        j--;
    }
}

void solve3() {
    vector<int> p, q;
    fill(&vis[1], &vis[n + 1], false);

    for (int i = 1; i <= n; i++) {
        vector<int> pos;
        int j = i;

        while (!vis[j]) {
            pos.push_back(j);
            vis[j] = true;
            j = h[j];
        }

        split_cycle(pos, p, q);
    }

    print_round(p, q);
}

int main() {
    scanf("%d", &n);

    for (int i = 1; i <= n; i++)
        scanf("%d", &h[i]);

    scale();

    int lc = longest_cycle();

    if (lc == 1) {
        printf("0\n");
    } else if (lc == 2) {
        printf("1\n");
        solve2();
    } else {
        printf("2\n");
        solve3();
        solve2();
    }

    return 0;
}