基于 2 进制 MSD 基数排序实现全局逆序对计数
Untitled_unrevised · · 题解
本文介绍使用 2 进制 MSD 基数排序计算全局逆序对数量的做法。
2 进制 MSD 基数排序
我们首先简述 2 进制的 MSD 基数排序的算法流程:
- 确定最大的位数
s = \lceil\log_2(\max a)\rceil ,对于本题来说小于等于30 ; - 从高到低枚举 2 进制数位,此时数位为
0 的必然小于数位为1 的;将数位为0 的移到左边,数位为1 的移到右边,然后分别递归,直至数组长度小于等于1 或者数位枚举完毕。
算法改造
照着这个思路,对于第 2 步,如果发现数位为
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;
}
之后为了不重复计数,我们将将数位为
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;
}
这样便做完了,时间复杂度
原谅我代码写得有点炫技(