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
#include<cstdio>
#include<vector>
#include<algorithm>
#include<map>
#include<utility>

using namespace std;

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

    vector<int> heights(graduatesNum);
    vector<int> sortedHeights(graduatesNum);
    for (int i = 0; i < graduatesNum; i++) {
        scanf("%d\n", &heights[i]);
        sortedHeights[i] = heights[i];
    }

    sort(sortedHeights.begin(), sortedHeights.end());
    map<int, int> targetIxs;
    for (int i = 0; i < graduatesNum; i++) {
        targetIxs[sortedHeights[i]] = i;
    }

    vector<bool> processed(graduatesNum, false);
    vector<vector<pair<int, int> > > swaps;

    for (int i = 0; i < graduatesNum; i++) {
        if (!processed[i]) {
            vector<int> cycle;
            int startHeight = heights[i];
            cycle.push_back(i);
            processed[i] = true;

            int j = targetIxs[startHeight];
            while (j != i) {
                cycle.push_back(j);
                processed[j] = true;
                j = targetIxs[heights[j]];
            }

            bool added = true;
            int range = 1;
            int turn = 0;

            while (added) {
                added = false;
                int k = 0;
                int first = -1;

                while (k < cycle.size()) {
                    if (first == -1) {
                        first = cycle[k];
                    } else {
                        
                        while (turn >= swaps.size()) {
                            vector<pair<int, int> > layer;
                            swaps.push_back(layer);
                        }

                        pair<int, int> swapPair(first, cycle[k]);
                        swaps[turn].push_back(swapPair);

                        added = true;
                        first = -1;
                    }

                    k += range;
                }

                range *= 2;
                turn++;
            }
        }
        
    }

    printf("%lu\n", swaps.size());
    for (int i = 0; i < swaps.size(); i++) {
        printf("%lu\n", swaps[i].size() * 2);
        for (int j = 0; j < swaps[i].size(); j++) {
            printf("%d ", swaps[i][j].first + 1);
        }

        for (int j = swaps[i].size() - 1; j > 0; j--) {
            printf("%d ", swaps[i][j].second + 1);
        }
        printf("%d\n", swaps[i][0].second + 1);
    }
}