簡體   English   中英

計算數組中的求反數,C ++

[英]Counting the number of inversions in an array, C++

大小為n的數組a求逆稱為對(i,j) ,對它認為i<ja[i]>a[j] 我試圖在C ++中實現一個函數,該函數計算給定數組中的反轉次數。 我遵循了分而治之的方法,該方法只是修改了合並排序算法,並在O(n log n)時間內運行。 到目前為止,這是我的代碼:

long long int glob;

template< class T >
long long int merge( T *arr, int beg, int mid, int end ) {
  queue< int > left;
  queue< int > right;

  for( int i=beg; i<=mid; ++i ) {
    left.push( arr[i] );
  }
  for( int i=mid+1; i<=end; ++i ) {
    right.push( arr[i] );
  }

  int index=beg;
  int ret=0;

  while( !left.empty() && !right.empty() ) {
    if( left.front() < right.front() ) {
      arr[index++] = left.front();
      left.pop();
    } else {
      arr[index++] = right.front();
      right.pop();
      ret+=left.size();
    }
  }

  while( !left.empty() ) { arr[index++]=left.front();left.pop(); }
  while( !right.empty() ) { arr[index++]=right.front();right.pop(); }

  return ret;
}

template< class T >
void mergesortInvCount( T *arr, int beg, int end ) {
  if( beg < end ) {
    int mid = (int)((beg+end)/2);
    mergesortInvCount( arr, beg, mid );
    mergesortInvCount( arr, mid+1, end );
    glob += merge( arr, beg, mid, end );
  }
}

對於某些測試用例,它可以產生正確的結果,但對於另一些測試用例,則給出錯誤的輸出。 我是否對算法有錯誤的理解,或者在實現上做錯了? 有人可以幫我嗎? 提前致謝。

Test case: 2 1 3 1 2
Correct: 4
Mine: 6

我沒有檢查代碼中的所有步驟,但是您的代碼行

if( left.front() < right.front() )

建議我,在else分支中,“ ret”不僅在a(j)> a(i)時增加,而且在它們相等時也增加,這與您對案件的描述不符。 因此,也許您應該嘗試將上面引用的行更改為:

if( left.front() <= right.front() )

問候

考試

if( left.front() < right.front() )

應該是<= 現在,您要從右半邊移出相同的值,然后再從左半邊移出相同的值,然后計算不是的倒數(每次出現都會計數左虛假反轉中的相同項目數)。 在您的示例中,您必須復制對,每個對都創建一個幻像倒置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM