基于 2 进制 MSD 基数排序实现全局逆序对计数

· · 题解

本文介绍使用 2 进制 MSD 基数排序计算全局逆序对数量的做法。

2 进制 MSD 基数排序

我们首先简述 2 进制的 MSD 基数排序的算法流程:

  1. 确定最大的位数 s = \lceil\log_2(\max a)\rceil,对于本题来说小于等于 30;
  2. 从高到低枚举 2 进制数位,此时数位为 0 的必然小于数位为 1 的;将数位为 0 的移到左边,数位为 1 的移到右边,然后分别递归,直至数组长度小于等于 1 或者数位枚举完毕。

算法改造

照着这个思路,对于第 2 步,如果发现数位为 0 的,则它前面所有的数位为 1 的都比它大,假设有 k 个,那么就产生了 k 个逆序对,把它累加进答案即可。

using u32 = unsigned int;
using u64 = unsigned long long;

array<u64, 2> cnt;

template<class ForIt, class RanIt, class UnFunc>
u64 counting_sort(
    ForIt first, ForIt last,
    RanIt dest, UnFunc key
) {

    fill(cnt.begin(), cnt.end(), 0);
    u64 res = 0;

    for_each(first, last, [&](u32 x) {
        u64 k = key(x);
        if(k == 0) {
            res += cnt[1]; // 累加产生的逆序对数
        }
        ++cnt[k];
    });

    // ...

    return res;
}

之后为了不重复计数,我们将将数位为 0 的移到左边,数位为 1 的移到右边。为了不影响剩下部分的逆序对数量,移动时应当保持数位相同元素的先后次序,然后再对各自的区间进行递归。为了实现这些,我们可以直接照抄计数排序,先将结果保存到辅助数组里之后再复制回去。

using u32 = unsigned int;
using u64 = unsigned long long;

array<u64, 2> cnt;

template<class ForIt, class UnFunc>
u64 counting_sort(
    ForIt first, ForIt last,
    UnFunc key
) {

    u64 res = 0;
    u64 len = last - first;
    fill(cnt.begin(), cnt.end(), 0);
    unique_ptr<u32[]> dst =
        make_unique_for_overwrite<u32[]>(len); // 临时数组

    for_each(first, last, [&](u32 x) {
        u64 k = key(x);
        if(k == 0) {
            res += cnt[1]; // 累加产生的逆序对数
        }
        ++cnt[k];
    });

    cnt[1] = cnt[0];
    cnt[0] = 0;

    for_each(first, last, [&](u32 x) {
        dst[cnt[key(x)]++] = x; // 存储到 dst 上
    });
    copy(dst.get(), dst.get() + len, first); // 复制回 first

    return res;
}

然后是 MSD 基数排序的递归部分:

using u32 = unsigned int;
using u64 = unsigned long long;

array<u64, 2> cnt;

template<class ForIt, class RanIt, class UnFunc>
u64 counting_sort(ForIt first, ForIt last, UnFunc key) {
    // 见上
}

template<class RanIt>
u64 msd_radix_sort(RanIt first, RanIt last, int shift = 29) {

    u64 len = last - first;

    if(len <= 1) {
        return 0;
    }

    u64 res = counting_sort(
        first, last,
        [=](u32 x) {
            return (x >> shift) & 1;
        }
    );

    if(shift != 0) {
        auto mid = first + cnt[0];
        res += msd_radix_sort(first, mid, shift - 1);
        res += msd_radix_sort(mid,  last, shift - 1);
    }

    return res;
}

这样便做完了,时间复杂度 O(n \log W)。

原谅我代码写得有点炫技(