Advertisement
JohnByte

PartDiv

Nov 18th, 2017
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.00 KB | None | 0 0
  1. import heapq
  2.  
  3. invs = 0
  4. def Merge(arr1, arr2):
  5.     global invs
  6.     mArr = []
  7.     L1, L2 = 0, 0
  8.     while len(arr1[L1:]) > 0 and len(arr2[L2:]) > 0:
  9.         if arr1[L1] > arr2[L2]:
  10.             invs += len(arr1[L1:])
  11.             mArr.append(arr2[L2])
  12.             L2 += 1
  13.         else:
  14.             mArr.append(arr1[L1])
  15.             L1 += 1
  16.     if len(arr1[L1:]) > 0:
  17.         mArr += arr1[L1:]
  18.     elif len(arr2[L2:]) > 0:
  19.         mArr += arr2[L2:]
  20.     return mArr
  21.  
  22. def MergeSort(arr):
  23.     h = []
  24.     for i in arr:
  25.         heapq.heappush(h, [i])
  26.     while len(h) > 1:
  27.         mrg = Merge(heapq.heappop(h), heapq.heappop(h))
  28.         heapq.heappush(h, mrg)
  29.     return heapq.heappop(h)
  30.  
  31.    
  32. def main():
  33.     global invs
  34.     n = int(input())
  35.     arr = [int(i) for i in input().split()]
  36.     MergeSort(arr)
  37.     print(invs)
  38.  
  39. if __name__ == "__main__":
  40.     main()
  41.  
  42. """при входных данных:
  43.     5
  44.     2 3 9 2 9
  45. Переменная invs = 0, хотя должно быть: invs = 2"""
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement