import sys
def get_number_of_inversions(a, b, left, right):
number_of_inversions = 0
if right - left <= 1:
return number_of_inversions
ave = (left + right) // 2
number_of_inversions += get_number_of_inversions(a, b, left, ave)
number_of_inversions += get_number_of_inversions(a, b, ave, right)
#write your code here
return number_of_inversions
if __name__ == '__main__':
input = sys.stdin.read()
n, *a = list(map(int, input.split()))
b = n * [0]
print(get_number_of_inversions(a, b, 0, len(a)))
此代码只能在“在此处编写代码”区域中实现
以及我整天想做的事情:
i=left
j=ave
k=left
temp_num=0
while i<ave and j<right:
if a[i]<=a[j]:
b[k]=a[i]
i+=1
else:
b[k]=a[j]
j+=1
temp_num += (ave-i)
k+=1
number_of_inversions+=temp_num
第二次尝试不那么聪明:
left=a[:ave]
right=a[ave:]
result = list()
i,j = 0,0
inv_count = 0
while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
elif right[j] < left[i]:
result.append(right[j])
j += 1
inv_count += (len(left)-i)
result += left[i:]
result += right[j:]
number_of_inversions +=inv_count
对我来说最有问题的是:
程序开始运行时使用比实际大的正确索引 首先进行递归调用 程序不返回子数组而只返回反转数
请给我一些如何实现该代码的建议
答案 0 :(得分:0)
我不确定你要做什么
但问题可能在这里right - left <= 1
我认为它应该是right <= left