定义
康托展开是一个全排列到一个自然数的双射,常用于构建哈希表时的空间压缩。 康托展开的实质是计算当前排列在所有由小到大全排列中的顺序,因此是可逆的。
算法
其中 ai 表示原数的第 i 位数字后面比自身小的数字的个数
例如
51423 = 4 * 4! + 0 * 3! + 2 * 2! + 0 * 1! + 0 * 0! = 100
每个 ai 的得出依据是:
-
5后面有4个数比5小
-
1后面有0个数比1小
-
4后面又2个数比4小
-
2后面有0个数比2小
-
3后面有0个数比3小
再由100逆回原来的排列
-
100 / 4! = 4 * 4! + 4 说明在[1,2,3,4,5]中比该位小的数字有4个,故第一位是5
-
4 / 3! = 0 * 3! + 4 说明在[1,2,3,4]中比第该位小的数字有0个,故第二位是1
-
4 / 2! = 2 * 2! + 0 说明在[2,3,4]中比该位小的数字有2个,故第三位是4
-
0 / 1! = 0 * 1! + 0 说明在[2,3]中比该位小的数字有0个,故第四位是2
-
0 / 0! = 0 * 0! + 0 说明在[3]中比该位小的数字有0个,故第五位是3
所以对应100的原排列是 51423
康托展开
C++
vector<int> c({ 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 });
int cantor(vector<int>& permutation)
{
int res = 0;
for (int i = 0; i < permutation.size(); i++)
{
int a = 0;
for (int j = i + 1; j < permutation.size(); j++)
{
if (permutation[i] > permutation[j])
a++;
}
res += a * c[permutation.size() - i - 1];
}
return res;
}
Python
c = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
def cantor(permutation: list) -> int:
global c
res = 0
n = len(permutation)
for i in range(n):
res += c[n - i - 1] * len(list(filter(lambda x: permutation[i] > x, permutation[i+1:])))
return res
逆康托展开
C++
vector<int> c({ 1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880 });
vector<int> decantor(int num, int n)
{
vector<int> res;
vector<int> nums;
for (int i = 1; i <= n; i++) nums.push_back(i);
for (int i = n - 1; i >= 0; i--)
{
int a = num / c[i];
res.push_back(nums[a]);
nums.erase(nums.begin() + a);
num -= a * c[i];
}
return res;
}
Python
c = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
def decantor(num: int, n: int) -> list:
global c
res = list()
nums = [i for i in range(1, n + 1)]
for i in range(n - 1, -1, -1):
a = num // c[i]
res.append(nums[a])
nums.pop(a)
num -= a * c[i]
return res