P1908 逆序对 python题解(归并排序,只能通过前10,其他超时)

n=int(input())
a=list(map(int,input().split()))
s=0
def msort(alist):
    if len(alist)<=1:
        return alist
    m=len(alist)//2
    llist=msort(alist[:m])
    rlist=msort(alist[m:])
    return merge(llist,rlist)

def merge(left,right):
    #print(left,right)
    ll=0
    rr=0
    temp=[]
    while ll<len(left) and rr<len(right):
        if left[ll]<=right[rr]:
            temp.append(left[ll])
            ll+=1
        else:
            #print(left[ll],right[rr])
            temp.append(right[rr])
            rr+=1 
            global s          
            s+=len(left)-ll
            #print("s",s)
    temp+=left[ll:]   
    temp+=right[rr:]
    return temp
a=msort(a)
#print(a)
print(s)

你可能感兴趣的:(python,算法)