逆序數(歸併排序)

來源:互聯網
上載者:User

標籤:cpp   turn   void   amp   class   歸併排序   大小   python   out   

在一個排列中,如果一對數的前後位置與大小順序相反,即前面的數大於後面的數,那麼它們就稱為一個逆序。一個排列中逆序的總數就稱為這個排列的逆序數。

如2 4 3 1中,2 1,4 3,4 1,3 1是逆序,逆序數是4。給出一個整數序列,求該序列的逆序數。Input
第1行:N,N為序列的長度(n <= 50000)第2 - N + 1行:序列中的元素(0 <= A[i] <= 10^9)
Output
輸出逆序數
Input樣本
42431
Output樣本
4


這題用歸併排序做
#include <bits/stdc++.h>using namespace std;const int Maxn = 50010;int A[Maxn];int tmp[Maxn];int cnt = 0;void msort( int* A,int* tmp,int bg,int ed ){    if( ed - bg > 1 ){        int mid = bg + (ed-bg)/2;        int x = bg;        int y = mid;        msort( A,tmp,bg,mid );        msort( A,tmp,mid,ed );        int index = bg;        while( x < mid && y < ed ){            if( A[x] > A[y] ){                cnt += mid - x;//如果滿足x < y and A[x] > A[y],即逆序,就加(mid-x),因為當前的A[x] > A[y],那麼A[x]後面的所有數字都 > A[y],                tmp[index++] = A[y++];            }else{                tmp[index++] = A[x++];            }        }        while( x < mid ){            tmp[index++] = A[x++];        }        while( y < ed ){            tmp[index++] = A[y++];        }        for( int i = bg; i < ed; i++ ){            A[i] = tmp[i];        }    }}int main(){    int n;    cin >> n;    for( int i = 0; i < n; i++ ){        cin >> A[i];    }    msort(A,tmp,0,n);    cout << cnt << "\n";}

 以下是python代碼

def sortandcount( alist ):    n = len( alist )    count = 0    if n == 2 or n == 1:        if n == 2:            if alist[0] > alist[1]:                alist = alist[::-1]                count += 1        return alist,count    a,cnt1 = sortandcount( alist[:n/2] )    b,cnt2 = sortandcount( alist[n/2:] )    count += cnt1 + cnt2    resList = [0]*n    i = j = 0    len1 = len( a )    len2 = len( b )    for k in range( n ):        if i < len1 and j < len2:            if a[i] < b[j]:                resList[k] = a[i]                i += 1            else:                resList[k] = b[j]                count += len1 - i;                j += 1        elif i < len1:            resList[k] = a[i]            i += 1        else:            resList[k] = b[j]            j += 1    return resList ,countdef main():    n = input()    num = [ input() for i in range(n) ]    i,c = sortandcount(num)    print cif __name__ == ‘__main__‘:    main()

 

逆序數(歸併排序)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.