繁体   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