標籤: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()
逆序數(歸併排序)