1. 程式人生 > >Cantor expansion and deCantor expansion

Cantor expansion and deCantor expansion

Cantor expansion is a way to use the Full Permutation and the id in the Permutation.In this way to map the id and the permutation,we can create a easy hash.It can be said a the most easy hash.
\(ans=a_{0}\cdot (n-1)!+a_{1}\cdot(n-2)!+\cdot\cdot\cdot+a_{n-1}\cdot(n-(n-1))!+a_{n}\cdot(n-n)!\)
the \(a_{i}\)
is the num in the others.

deCantor expansion is a opposite progress.

#include<bits/stdc++.h>
using namespace std;
int f[]={1,1,2,6,24,120};
int a[5];
void contorExpanse(){//康拓展開
    int ans=0;
    for(int i=0;i<5;i++){
        int tmp=0;
        for(int j=i+1;j<5;j++){
            if(a[j]<a[i]) tmp++;//計數        }
        ans+=tmp*f[5-i-1];//當前計數*階乘    }
    cout
<<ans<<endl; } void anticontorExpanse(int n){ //寫的非常混亂 /* 整理一下思路就是設計兩個動態陣列作為可選和結果 從n->1開始,不斷的輾轉相除 計算當前小於該數的個數,從可選中選擇,並刪除 此時該數變成餘數,重複步驟 */ vector<int>k; for(int i=1;i<=5;i++) k.push_back(i); vector<int>contor; int tmp=n; for(int i=5;i>=1;i--){ int cc=tmp/(f[i-1]);//計算當前的計數 contor.push_back(k[cc]); k.erase(k.begin()+cc);//刪除 tmp=tmp%f[i-1];//變成餘數 } for(int i=0;i<contor.size();i++) cout<<contor[i]<<" "; } int main(){ for(int i=0;i<5;i++) cin>>a[i]; contorExpanse(); int n; cin>>n; anticontorExpanse(n); return 0; }