The Cantor expansion is a bijection arranged to a natural number. So reversible.
-
Cantor expansion: given a number n, and a complete arrangement of n bits, find out the number X of this arrangement
-
Inverse Cantor expansion: given a number n, and the number X of this arrangement, find this arrangement
Here X (note that the first arrangement is X = 0, so for convenience, we can directly +1 later.)
An means that in the order from (1,2,3, ... n), it is less than an and is not arranged The number.
Such as 34152,
- a5 = 2 (only 1,2 is less than 3)
- a4 = 2 (3 is ranked, only 1,2 is less than 4)
- a3 = 0 (nothing smaller than 1)
- a2 = 1 (1, 3, 4 are arranged, only 2 less than 5)
- a1 = 0
Kang expands code implementation, complexity O (N * N)
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int factorial[20]={1,1,2,6,24,120,720,5040,40320,362880,3628800};
int flag[20];
void cantor(int *num,int n){
int x=0;
int tep=n-1;
for(int i=1;i<=n;i++){//遍历num数组
int cot=0;
for(int j=1;j<num[i];j++)//找到小于num[i]的数字
{
if(j<num[i]&&flag[j]==0) cot++;
}
flag[num[i]]=1;
x+=cot*factorial[tep--];
}
cout<<x+1;
}
int main(void)
{
int num[20]={0,3,4,1,5,2};//求34152在排列中排多少
int n=5;
cantor(num,n);//n位
}
The output 34152 is the 62nd permutation
Reverse expansion
The problem of adding X without adding 1 was discussed earlier. If it is +1, it needs -1; if it is not +1, -1 is not needed.
For example, n = 5, x = 62, the arrangement is 34152, see how to calculate a5, a4 ...
- First minus one: x = 61
- a5 = x / 4! = 61/4! = 2, indicating that there are two smaller than the first, so a5 = 3. x = 61% 4! = 13
- a4 = 13/3! = 2, indicating that the first place is removed, there are two smaller than the second, so a4 = 4. X = 13% 3! = 1
- a3 = 1/2! = 0, it means that the first and second digits are removed, there are 0 less than third digit, so a3 = 1 x = 1% 2! = 1
- a4 = 1/1! = 1, so a4 = 5. x = 1% 1 = 0
- a5 = 0/1 = 0, so a5 = 2. The last number
is 34152.
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int factorial[20]={1,1,2,6,24,120,720,5040,40320,362880,3628800};
int nums[20]={0,1,2,3,4,5,6,7,8,9,10};
vector<int>num(nums+1,nums+11);
void decantor(int n,int x){
vector<int>ans;
for(int i=n;i>=1;i--){
int a=x/factorial[i-1];
x=x%factorial[i-1];
ans.push_back(num[a]);
num.erase(num.begin()+a);
}
for(auto a:ans) cout<<a;
}
int main(void)
{
int n=5;
int x=62;
decantor(n,x-1);//n位
}