康托展开 逆康托展开
{1,2,3} 三个数的全排列可看做6个数字,按从小到大排序得到序列a:123,132,213,231,312,321
下面有两种提问:
1.数字231在序列a中排名第几?回答4
2.数列a中排名第5的数字是多少?回答312
给出n个数字(1,2,3,…,n),回答关于序列a的1和2两种提问。
int cantor(int s[10]){//从高位到低位依次存着一个[1,9]数字
int Ans=(s[1]-1)*Fact[n-1];
for(int i=2;i<=n;i++){
int t=1;//数字从1开始
for(int j=1;j<i;j++)
if(s[j]<s[i])t++;
Ans+=(s[i]-t)*Fact[n-i];
}
return Ans;
}
void decantor(int x){
int s[10]={0};x--;
bool used[10]={0};
for(int t=x,cnt=n;t;t/=10,cnt--)
s[cnt]=t%10;
for(int i=1;i<=n;i++){
int t=x/Fact[n-i],j;
for(j=1;j<=n;j++)
if(!used[j]){if(!t)break;t--;}
used[j]=true,s[i]=j;
x%=Fact[n-i];
}
for(int i=1;i<=n;i++)printf("%d",s[i]);
puts("");
return;
}
xx_permutation的用法
有些题不用康托展开,可以用next_permutation
(往后走)或者prev_permutation
(往前走)直接做。
比如对整型数组A的[1,5]排序,就有next_permutation(A+1,A+5+1);
比如对string类型的str排序,就有next_permutation(str.begin(),str.end());