#!/usr/bin/env python3 n = int(input()) heights = [int(input()) for i in range(n)] sorted_heights = [x for x in heights] sorted_heights.sort() order_dict = {sorted_heights[i]: i for i in range(n)} perm = [order_dict[h] for h in heights] def permutation_cycles(p): sz = len(p) vis = [False] * sz ans = [] for i in range(sz): if vis[i]: continue cycle = [i] cur = p[i] vis[i] = True while cur != i: vis[cur] = True cycle.append(cur) cur = p[cur] ans.append(cycle) return ans res = [] while perm != list(range(n)): prefix = [] suffix = [] for cycle in permutation_cycles(perm): sz = len(cycle) if sz == 1: continue for i in range(sz // 2): prefix.append(cycle[i]) suffix.append(cycle[-i - 1]) desc = prefix + suffix[::-1] res.append([x + 1 for x in desc]) for i in range(len(desc) // 2): a, b = desc[i], desc[-i - 1] perm[a], perm[b] = perm[b], perm[a] print(len(res)) for line in res: print(len(line)) print(*line)
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 | #!/usr/bin/env python3 n = int(input()) heights = [int(input()) for i in range(n)] sorted_heights = [x for x in heights] sorted_heights.sort() order_dict = {sorted_heights[i]: i for i in range(n)} perm = [order_dict[h] for h in heights] def permutation_cycles(p): sz = len(p) vis = [False] * sz ans = [] for i in range(sz): if vis[i]: continue cycle = [i] cur = p[i] vis[i] = True while cur != i: vis[cur] = True cycle.append(cur) cur = p[cur] ans.append(cycle) return ans res = [] while perm != list(range(n)): prefix = [] suffix = [] for cycle in permutation_cycles(perm): sz = len(cycle) if sz == 1: continue for i in range(sz // 2): prefix.append(cycle[i]) suffix.append(cycle[-i - 1]) desc = prefix + suffix[::-1] res.append([x + 1 for x in desc]) for i in range(len(desc) // 2): a, b = desc[i], desc[-i - 1] perm[a], perm[b] = perm[b], perm[a] print(len(res)) for line in res: print(len(line)) print(*line) |