AcWing 788. 逆序对的数量 简单归并排序求解
原题链接
简单
作者:
皓首不倦
,
2020-08-06 23:21:55
,
所有人可见
,
阅读 480
n = int(input())
arr = list( map(int, input().split()) )
ans = [0]
def merge_sort(arr):
if len(arr) <= 1:
return arr
n = len(arr)
mid = (n-1) // 2
arr1, arr2 = arr[:mid+1], arr[mid+1:]
merge_sort(arr1)
merge_sort(arr2)
for val in arr1:
l, r = 0, len(arr2)-1
pos = -1
while l <= r:
m = l + (r-l) // 2
if arr2[m] < val:
pos = m
l = m + 1
else:
r = m - 1
if pos != -1:
ans[0] += pos+1
arr.sort()
return arr
merge_sort(arr)
print(ans[0])