def main(): n = int(input()) array = [] inverted = {} for idx in range(n): h = int(input().strip()) array.append(h) inverted[h] = idx desired_array = sorted(array) inverted_desired = {val: idx for idx, val in enumerate(desired_array)} waiting = set(array) results = [] while waiting: processed = set() pairs = [] to_remove = [] for item in waiting: if item in processed: continue item_position = inverted[item] if desired_array[item_position] == item: to_remove.append(item) continue desired_position = inverted_desired[item] other_item = array[desired_position] if other_item in processed: continue array[item_position], array[desired_position] = array[desired_position], array[item_position] inverted[item], inverted[other_item] = inverted[other_item], inverted[item] processed.add(item) processed.add(other_item) to_remove.append(item) pairs.append((item_position + 1, desired_position + 1)) for item in to_remove: waiting.remove(item) if pairs: results.append(pairs) print(len(results)) for pairs in results: print(2 * len(pairs)) print(' '.join(str(p[0]) for p in pairs), end=' ') print(' '.join(str(p[1]) for p in reversed(pairs))) 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 49 50 51 | def main(): n = int(input()) array = [] inverted = {} for idx in range(n): h = int(input().strip()) array.append(h) inverted[h] = idx desired_array = sorted(array) inverted_desired = {val: idx for idx, val in enumerate(desired_array)} waiting = set(array) results = [] while waiting: processed = set() pairs = [] to_remove = [] for item in waiting: if item in processed: continue item_position = inverted[item] if desired_array[item_position] == item: to_remove.append(item) continue desired_position = inverted_desired[item] other_item = array[desired_position] if other_item in processed: continue array[item_position], array[desired_position] = array[desired_position], array[item_position] inverted[item], inverted[other_item] = inverted[other_item], inverted[item] processed.add(item) processed.add(other_item) to_remove.append(item) pairs.append((item_position + 1, desired_position + 1)) for item in to_remove: waiting.remove(item) if pairs: results.append(pairs) print(len(results)) for pairs in results: print(2 * len(pairs)) print(' '.join(str(p[0]) for p in pairs), end=' ') print(' '.join(str(p[1]) for p in reversed(pairs))) if __name__ == "__main__": main() |