-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
59 lines (43 loc) · 1.28 KB
/
main.py
File metadata and controls
59 lines (43 loc) · 1.28 KB
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
from collections import defaultdict
from sys import stdin
def find_cycles(permutation):
n = len(permutation)
visited = [False] * n
cycles = []
stack = []
def dfs(i):
visited[i] = True
stack.append(i)
while stack:
j = permutation[stack[-1]] - 1
if not visited[j]:
return dfs(j)
else:
if j == i:
cycle = stack[:]
while cycle:
visited[cycle.pop()] = False
cycles.append(cycle)
elif j >= n:
break
for i in range(n):
if not visited[i]:
dfs(i)
return cycles
def reverse_cycle(permutation, cycle, signs):
for i, j in zip(cycle, cycle[::-1]):
permutation[i] = j
signs[i] = not signs[i]
def solve(n, permutation):
signs = [True] * n
cycles = find_cycles(permutation)
answer = len(cycles)
for cycle in cycles:
reverse_cycle(permutation, cycle, signs)
return answer, [(cycle[0] + 1, cycle[-1] + 1) for cycle in cycles]
n = int(stdin.readline())
permutation = list(map(int, stdin.readline().split()))
answer, operations = solve(n, permutation)
print(answer)
for a, b in operations:
print(a, b)