import sys
def genswaps(tab, sorted, pos):
skip = set()
swapL = []
swapR = []
for i in range(len(tab)):
if tab[i] != sorted[i] and i not in skip:
d = pos[tab[i]]
cycle = [i, d]
while pos[tab[d]] != i:
d = pos[tab[d]]
cycle.append(d)
cl = len(cycle)
ofs = 0
while cl >= 2:
a, b = cycle[ofs], cycle[ofs + cl - 1]
swapL.append(a + 1)
swapR.append(b + 1)
tab[a], tab[b] = tab[b], tab[a]
ofs += 1
cl -= 2
skip.update(cycle)
swapR.reverse()
swapL.extend(swapR)
return swapL
def main():
lines, *arr = map(int, sys.stdin.read().splitlines())
plan = arr.copy()
plan.sort()
pos = {}
for i in range(lines):
pos[plan[i]] = i
swaps = []
while arr != plan:
swaps.append(genswaps(arr, plan, pos))
print(len(swaps))
for moves in swaps:
print(len(moves))
print(*moves)
if __name__ == "__main__":
main()
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 | import sys def genswaps(tab, sorted, pos): skip = set() swapL = [] swapR = [] for i in range(len(tab)): if tab[i] != sorted[i] and i not in skip: d = pos[tab[i]] cycle = [i, d] while pos[tab[d]] != i: d = pos[tab[d]] cycle.append(d) cl = len(cycle) ofs = 0 while cl >= 2: a, b = cycle[ofs], cycle[ofs + cl - 1] swapL.append(a + 1) swapR.append(b + 1) tab[a], tab[b] = tab[b], tab[a] ofs += 1 cl -= 2 skip.update(cycle) swapR.reverse() swapL.extend(swapR) return swapL def main(): lines, *arr = map(int, sys.stdin.read().splitlines()) plan = arr.copy() plan.sort() pos = {} for i in range(lines): pos[plan[i]] = i swaps = [] while arr != plan: swaps.append(genswaps(arr, plan, pos)) print(len(swaps)) for moves in swaps: print(len(moves)) print(*moves) if __name__ == "__main__": main() |
English