计算按递增顺序排列序列所需的反转次数

Calculating the number of inversions in a sequence required to arrange it in increasing order

输入的形式为

5
2 3 9 2 9

输出应该是按照从小到大的顺序排列序列应该进行的反转次数。即新序列将是 2 2 3 9 9 并从输入中产生这个序列 2 反演了。

2

所以基本上我认为我需要做的是,将输入转换为数组,然后 运行 下面的代码

k = int(input())
str = input()
def getInvCount(arr, n):

inv_count = 0
for i in range(n):
    for j in range(i + 1, n):
        if (arr[i] > arr[j]):
            inv_count += 1

return inv_count

arr = str.split() 
n = len(arr)
print(getInvCount(arr, n))

或者我什至试过这个代码

k = int(input())
def mergeSort(arr, n):

temp_arr = [0]*n
return _mergeSort(arr, temp_arr, 0, n-1)

def _mergeSort(arr, temp_arr, left, right):

inv_count = 0

if left < right:

    mid = (left + right)//2

    inv_count += _mergeSort(arr, temp_arr,
                                left, mid)

    inv_count += _mergeSort(arr, temp_arr,
                              mid + 1, right)

    inv_count += merge(arr, temp_arr, left, mid, right)
return inv_count

def merge(arr, temp_arr, left, mid, right):
i = left
j = mid + 1
k = left
inv_count = 0

while i <= mid and j <= right:

    if arr[i] <= arr[j]:
        temp_arr[k] = arr[i]
        k += 1
        i += 1
    else:
        temp_arr[k] = arr[j]
        inv_count += (mid-i + 1)
        k += 1
        j += 1

while i <= mid:
    temp_arr[k] = arr[i]
    k += 1
    i += 1

while j <= right:
    temp_arr[k] = arr[j]
    k += 1
    j += 1

for loop_var in range(left, right + 1):
    arr[loop_var] = temp_arr[loop_var]
     
return inv_count

str = input()
arr = str.split()
n = len(arr)
result = mergeSort(arr, n)
print(result)

然而,第一个代码在某些情况下会超时,而第二个代码会在那里失败。我能得到一些帮助吗?

您可能忘记在将输入传递到合并排序之前将其转换为 int:

k = int(input())
def mergeSort(arr, n):

    temp_arr = [0]*n
    return _mergeSort(arr, temp_arr, 0, n-1)

def _mergeSort(arr, temp_arr, left, right):

    inv_count = 0

    if left < right:

        mid = (left + right)//2

        inv_count += _mergeSort(arr, temp_arr,
                                    left, mid)

        inv_count += _mergeSort(arr, temp_arr,
                                  mid + 1, right)

        inv_count += merge(arr, temp_arr, left, mid, right)
    return inv_count

def merge(arr, temp_arr, left, mid, right):
    i = left
    j = mid + 1
    k = left
    inv_count = 0

    while i <= mid and j <= right:

        if arr[i] <= arr[j]:
            temp_arr[k] = arr[i]
            k += 1
            i += 1
        else:
            temp_arr[k] = arr[j]
            inv_count += (mid-i + 1)
            k += 1
            j += 1

    while i <= mid:
        temp_arr[k] = arr[i]
        k += 1
        i += 1

    while j <= right:
        temp_arr[k] = arr[j]
        k += 1
        j += 1

    for loop_var in range(left, right + 1):
        arr[loop_var] = temp_arr[loop_var]
         
    return inv_count

str = input()
arr = list(map(int, str.split()))
n = len(arr)
result = mergeSort(arr, n)
print(result)