解题思路
枚举所有的可能的交换情况,时间复杂度 O ( n 4 ) O(n^4) O(n4)。
用归并排序计算数组的逆序对,时间复杂度 O ( n ) O(n) O(n)。
综上时间复杂度 O ( n 5 ) O(n^5) O(n5)。
由于 Python
运行效率较低,约
500
500
500 秒可得到结果。
N = 55
n = 51
a = [0] * N
tmp = [0] * N
def merge_sort(q, l, r):
if l >= r:
return 0
mid = (l + r) // 2
res = merge_sort(q, l, mid) + merge_sort(q, mid + 1, r)
i = l
j = mid + 1
k = 0
while i <= mid and j <= r:
if q[i] <= q[j]:
tmp[k] = q[i]
k += 1
i += 1
else:
tmp[k] = q[j]
res += mid - i + 1
k += 1
j += 1
while i <= mid:
tmp[k] = q[i]
k += 1
i += 1
while j <= r:
tmp[k] = q[j]
k += 1
j += 1
for i in range(l, l + k):
q[i] = tmp[i - l]
return res
cnt = 0
res = 0
for i in range(1, n + 1):
for j in range(1, n + 1):
if i != j:
for u in range(1, n + 1):
for v in range(1, n + 1):
if u != v:
cnt += 1
a = list(range(0, n + 1))
a[i], a[j] = a[j], a[i]
a[u], a[v] = a[v], a[u]
res += merge_sort(a, 1, n)
print("%.2lf" % (res / cnt))
运行结果:
65.33
【在线测评】