Lily's Homework

  • + 0 comments
    def f(a):
    	n = len(a)
    	a = [(a[x], x) for x in range(n)]
    	a1 = sorted(a)
    	a2 = [a1[x][1] for x in range(n)]
    	s = set()
    	swaps = 0
    	for i in range(n):
    		if i not in s:
    			d = a2[i]
    			s |= {d}
    			while d != i:
    				swaps += 1
    				d = a2[d]
    				s |= {d}
    	return swaps<br><br>
    n = int(input())
    a = list(map(int, input().split()))
    d = f(a)
    a.reverse()
    d1 = f(a)
    print(min(d, d1))
    

    The beautiful array is sorted array or reverse sorted array.

    Suppose the array is [5 4 2 3 1]

    Store it with its own index [(5, 0), (4, 1), (2, 2), (3, 3), (1, 4)]

    Sort the array with respect to data [(1, 4), (2, 2), (3, 3), (4, 1), (5, 0)]

    Extract shuffled indices [4, 2, 3, 1, 0]

    Now create cycles
    (0, 4) and (1, 2, 3)
    Go to 0th index of above array
    Value at this position is 4 so go to 4th index
    Value at new position is 0 which is same as start so stop

    Similarly 1 -> 2 -> 3

    1 is subtracted from each cycle length and then they are added (2 - 1) + (3 - 1) = 3

    This the swap for first case

    Now the input array is reversed as [1 3 2 4 5] and the above steps are repeated

    We get 2 values of swap counts. Print the minimum out of it.