Counting Inversions 统计逆序数算法

问题:

     Recall the problem of finding the number of inversions. As in the course, we are given a sequence of n numbers a1, ..., an, which we assume are all distinct, and we difine an inversionto be a pair i < j such that ai> aj.
    We motivated the problemof counting inversions as a good measure of how different two orderings are. However, one might feel that this measure is too sensitive. Let’s call a pair a significant inversionif i < j and ai> 3aj.
    Given an O(n log n) algorithm to count the number of significant inversions between two orderings.


答:

令序列a1,a2,…,an排好序后为b1,b2,…,bn,要求重要逆序对的数目,

设计算法如下: 

1) Sort-and-Count (L) 

{   

     If n=1  then 没有逆序对   

     else k=n/2,将L分成两个自序列A和B;    

     (N1,A) = Sort-and-Count(A);    

     (N2,B) = Sort-and-Count(B);    

     (N3,L) = Merge-and-Count(A,B);    

     return N= N1+ N2+ N3和排好序的表L 

}


2) Merge-and-Count(A,l,m,r) 

{

     令A[l…m]为L, A[m+1…r]为R;

      i = 1,j = 1, InversionCount =0;

      for  k = m  to  r  do    

          if  L[i] > R[j]  then       

               A[k] = L[i]        

               i++;

          if  L[i] > 3R[j] then       //进行逆序数的统计

              InversionCount = InversionCount + j - k      

          else        

              A[k] = R[j]       

              j++ ;

      end for    

}

            显然Merge-and-Count (A,B)的算法复杂度为cn 。

    令Sort-and-Count (L)的算法复杂度为T(n),

    则: T(n)≤2T(n/2)+cn可推出T(n)= O(n log n)




  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值