设A[1..n]是一个包含N个非负整数的数组。如果在i〈 j的情况下,有A〉A[j],则(i,j)就称为A中的一个逆序对。
例如,数组(3,1,4,5,2)的“逆序对”有<3,1>,<3,2><4,2><5,2>,共4个。
使用归并排序可以用O(nlogn)的时间解决统计逆序对个数的问题
定义:对于一个给定的数列,如果有i<j,且Ai>Aj,则称(i,j)为一逆序对.
要解决的问题是,给出一个数列,求出这个数列包含多少个逆序对

 

今天在《算法导论》上看到了这题,提示用归并算法,没想明白。在google搜了一下,有一些实现但是没讲清楚,后来自己动手做了一下算是弄明白了。

普通实现 O(n^2):

 1template<class Iterator>
 2int countInversePair(Iterator first, Iterator last)
 3{
 4    int count = 0;
 5    Iterator it;
 6    while(first != last)
 7    {
 8        it = first;
 9        while(it != last)
10        {
11            if(*it < *first)
12                count++;
13            it++;
14        }

15        first++;
16    }

17
18    cout << count << endl;
19
20    return count;
21}

 

 归并实现 O(nlogn):

 1int gCount = 0;
 2
 3template<class Iterator>
 4int merge(Iterator begin, Iterator mid, Iterator end)
 5{
 6    Iterator iL = begin;
 7    Iterator iR = mid;
 8
 9    int count = distance(begin, end);
10    vector<int> v(count);
11    vector<int>::iterator it = v.begin();
12
13    while(iL != mid && iR != end)
14    {
15        if(*iL <= * iR)
16        {
17            *it++ = *iL++;
18        }

19        else
20        {
21            gCount += distance(iL, mid);
22            *it++ = *iR++;
23        }

24    }

25
26    if(iL == mid) copy(iR, end, it);
27    if(iR == end) copy(iL, mid, it);
28
29    copy(v.begin(), v.end(), begin);
30
31    return 0;
32}

33
34template<class Iterator>
35int mergeSort(Iterator begin, Iterator end)
36{
37    int count, step;
38    count = distance(begin, end);
39
40    if(count <= 1)
41    {
42        return 0;
43    }

44
45    step = count / 2;
46
47    mergeSort(begin, begin + step);
48    mergeSort(begin + step, end);
49
50    merge(begin, begin + step, end);
51
52    return 0;
53}

 

重点在 gCount += distance(iL, mid)

逆序对数实质就是插入排序过程中要移动元素的次数。

归并的时候 前后两个序列都是有序的,可以把这个过程想象成插入排序,将第二个序列的内容插入到第一个有序的序列中

那么插入第二个序列中的元素时,要移动的元素的位数即第一个序列中还未插入到新序列中的元素的个数

即: distance(iL, mid)

 

 

posted on 2008-11-06 00:09  哈哈熊  阅读(5513)  评论(1编辑  收藏  举报