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
#include <bits/stdc++.h>
using namespace std;

pair<vector<vector<int>>, unsigned long> get_cycles(const vector<int *> &h) {
    vector<bool> handled(size(h));
    vector<vector<int>> cycles;
    unsigned long switches = 0;
    for (int i = 0; i < size(h); ++i) {
        if (handled[i]) continue;
        cycles.emplace_back();
        int j = i;
        while (!handled[j]) {
            cycles.back().push_back(j);
            handled[j] = true;
            j = *h[j];
        }
        switches += size(cycles.back()) >> 1 << 1;
    }
    return {cycles, switches};
}

void perform_round(const vector<vector<int>> &cycles, vector<int *> &h) {
    for (const auto &cycle : cycles) {
        for (int i = 0; i < size(cycle) / 2; ++i) {
            cout << cycle[i] + 1 << ' ';
            swap(h[cycle[i]], h[cycle[size(cycle) - i - 1]]);
        }
    }
    for (int k = (int)size(cycles) - 1; k >= 0; --k) {
        auto &cycle = cycles[k];
        for (int i = ((int)size(cycle) + 1) / 2; i < size(cycle); ++i) {
            cout << cycle[i] + 1 << ' ';
        }
    }
    cout << endl;
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    int n;
    cin >> n;
    vector<int *> h(n);
    for (int i = 0; i < n; ++i) {
        h[i] = new int;
        cin >> *h[i];
    }
    vector<int *> helper = h;
    sort(begin(helper), end(helper), [](auto p1, auto p2) { return *p1 < *p2; });
    for (int i = 0; i < n; ++i) {
        *helper[i] = i;
    }
    auto [cycles, switches] = get_cycles(h);
    unsigned long max_cycle_len = 0;
    for (int i = 0; i < size(cycles); ++i) {
        max_cycle_len = max(max_cycle_len, size(cycles[i]));
    }
    cout << (max_cycle_len == 1 ? 0 : max_cycle_len == 2 ? 1 : 2) << endl;
    if (max_cycle_len == 1) {
        return 0;
    }
    if (max_cycle_len > 2) {
        cout << switches << endl;
        perform_round(cycles, h);
    }
    auto [cycles2, switches2] = get_cycles(h);
    cout << switches2 << endl;
    perform_round(cycles2, h);
}