解题思路:
注意事项:
参考代码:
def mergeSort(arr):
if len(arr) <= 1:
return arr, 0
mid = len(arr) // 2
left, left_inv = mergeSort(arr[:mid])
right, right_inv = mergeSort(arr[mid:])
merged, merge_inv = merge(left, right)
return merged, left_inv + right_inv + merge_inv
def merge(left, right):
merged = []
inversions = 0
i, j = 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
merged.append(left[i])
i += 1
else:
merged.append(right[j])
inversions += len(left) - i
j += 1
while i < len(left):
merged.append(left[i])
i += 1
while j < len(right):
merged.append(right[j])
j += 1
return merged, inversions
n = int(input())
arr = list(map(int, input().split()))
_, inversions = mergeSort(arr)
print(inversions)
0.0分
1 人评分
C语言程序设计教程(第三版)课后习题11.1 (C语言代码)浏览:685 |
字符串问题 (C语言代码)浏览:1634 |
C语言程序设计教程(第三版)课后习题6.10 (C语言代码)浏览:588 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:504 |
C语言训练-数字母 (C语言代码)浏览:670 |
简单的for循环浏览:1495 |
C语言程序设计教程(第三版)课后习题5.8 (C语言代码)浏览:1322 |
字符串比较 (C语言代码)浏览:770 |
简单的a+b (C语言代码)浏览:444 |
C语言程序设计教程(第三版)课后习题7.3 (C语言代码)浏览:420 |