-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtranspositions.py
59 lines (42 loc) · 1.12 KB
/
transpositions.py
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
# This Python file uses the following encoding: utf-8
# Python Program to find the number of
# transpositions in a permutation
N = 1000001
visited = [0] * N;
# This array stores which element goes to which position
goesTo = [0] * N;
# For eg. in { 5, 1, 4, 3, 2 }
# goesTo[1] = 2
# goesTo[2] = 5
# goesTo[3] = 4
# goesTo[4] = 3
# goesTo[5] = 1
# This function returns the size of a component cycle
def dfs(i) :
# If it is already visited
if (visited[i] == 1) :
return 0;
visited[i] = 1;
x = dfs(goesTo[i]);
return (x + 1);
# This functio returns the number
# of transpositions in the permutation
def noOfTranspositions(P, n) :
# Initializing visited[] array
for i in range(1, n + 1) :
visited[i] = 0;
# building the goesTo[] array
for i in range(n) :
goesTo[P[i]] = i + 1;
transpositions = 0;
for i in range(1, n + 1) :
if (visited[i] == 0) :
ans = dfs(i);
transpositions += ans - 1;
return transpositions;
# Driver Code
if __name__ == "__main__" :
permutation = [ 5, 1, 4, 3, 2 ];
n = len(permutation);
print(noOfTranspositions(permutation, n));
# output: 3