【洛谷】P1116 車廂重組【python】
0.題意
本題目寫成入門的紅題總感覺有些不妥,至少是普及的級別了吧。徒手寫歸併也不是2min就能搞定的。
1.分析
用歸併排序求逆序數
本題主要有如下幾個點需要注意:
01.歸併排序用Python的寫法
02.python 中數組如果沒有申請足夠大小是無法直接通過下標訪問的
03.樣例輸入輸出的問題。本題的測試樣例採取了三種 不同的輸入方式:
a.以空格分割
b.以換行分割
c.以空格和換行分割
反正輸入的數據特別煩人,從C++轉Python真的是很不習慣。
2.代碼
N = 10005
res = 0
temp = [0] * N # 臨時數組,必須使用這種方式纔可以,如果直接用.append()的話,會出現問題
# 使用歸併排序
def mergeSort(left,right):
global res
global temp
if left >= right: # 直接返回
return
mid = (left+right)//2 # 直接二分
mergeSort(left,mid)
mergeSort(mid+1,right)
# 開始合併
index = tl = left
tr = mid + 1
while tl <= mid and tr <= right:
if arr[tl] <= arr[tr]:
temp[index] = arr[tl] # 開始賦值
tl += 1
index += 1
# 如果是從右側開始賦值,說明左側的值要大
if arr[tr] <= arr[tl]:
temp[index] = arr[tr] # 開始賦值
tr+=1
index+=1
res += (mid - tl + 1)
# 賦值剩餘的數組值
while tl<=mid:
temp[index]=arr[tl]
tl+=1
index+=1
while tr<=right:
temp[index] = arr[tr]
index+=1
tr+=1
res += (mid-tl+1)
# 寫回到arr 數組中
for i in range(left,right+1):
arr[i] = temp[i]
n = input()
n = int(n)
arr=[]
while len(arr)<n: # 如果沒有讀夠n個數字
num = input()
nums = num.strip().split()
nums = [int(i) for i in nums]
for i in nums:
arr.append(i)
#print(arr)
# 進行一個歸併排序
mergeSort(0,n-1)
# for i in range(n):
# print(arr[i],end = " ")
print(res)
"""
5
1 4 2 5 3
5
1
2
3
4
5
"""