问题:
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)