AcWing 107. 超快速排序
原题链接
简单
作者:
皓首不倦
,
2020-09-15 23:59:15
,
所有人可见
,
阅读 386
'''
归并排序求逆序对个数即可
'''
import bisect
def merge_sort(arr):
if len(arr) == 1:
return arr.copy(), 0
mid = (len(arr)-1) // 2
arr1, cnt1 = merge_sort(arr[:mid+1])
arr2, cnt2 = merge_sort(arr[mid+1:])
cnt = cnt1 + cnt2
for val in arr1:
idx = bisect.bisect_left(arr2, val)
if idx - 1 >= 0 and idx - 1 < len(arr2):
cnt += idx
arr.sort()
ret = arr.copy()
ret.sort()
return ret, cnt
while True:
n = int(input())
if n == 0:
break
arr = [0] * n
for i in range(n):
arr[i] = int(input())
print(merge_sort(arr)[1])