algorithm-in-python/math/permute/permute_cantor.c

76 lines
1.6 KiB
C
Raw Normal View History

2018-12-11 15:57:58 +08:00
/* mbinary
#########################################################################
# File : permute_cantor.c
# Author: mbinary
# Mail: zhuheqin1@gmail.com
2019-01-31 12:09:46 +08:00
# Blog: https://mbinary.xyz
2018-12-11 15:57:58 +08:00
# Github: https://github.com/mbinary
# Created Time: 2018-11-17 11:25
# Description:
#########################################################################
*/
#include<stdio.h>
//使用康托展开计算全排列, 下面存储的是0!,1!,2!...(n-1)!
2020-04-15 12:28:20 +08:00
long long int fac[100] = {};
void calFac(int n)
{
int i;
2020-04-15 12:28:20 +08:00
fac[0] = 1;
for (i = 1; i <= n; i++) {
fac[i] = i * fac[i - 1];
}
}
2020-04-15 12:28:20 +08:00
void permute(int *arr, int n, int sum)
{
/*sum表示全排列由小到大排序后的名次,从0 开始计数, 由名次求出 n位的排列存储到 arr 中*/
2020-04-15 12:28:20 +08:00
int i, j, ct = 0, k, ct2;
int flag[n];
2020-04-15 12:28:20 +08:00
for (i = 0; i < n; i++)flag[i] = 1;
for (i = n - 1; i >= 0; i--) {
for (j = i; j >= 0; j--) {
if (j * fac[i] <= sum) {
ct2 = 0;
for (k = 0; k < n; ++k) {
//printf("i%d j%d k%d\n",i,j,k);
2020-04-15 12:28:20 +08:00
if (flag[k] == 1)ct2++;
if (ct2 > j)break;
}
2020-04-15 12:28:20 +08:00
arr[ct++] = k;
2020-04-15 12:28:20 +08:00
flag[k] = 0;
sum -= j * fac[i];
break;
}
}
}
}
2020-04-15 12:28:20 +08:00
void printArr(int *p, int n)
{
2020-04-15 12:28:20 +08:00
for (int i = 0; i < n; ++i)printf("%d, ", p[i]);
printf("\n");
}
int main()
{
2020-04-15 12:28:20 +08:00
int n = 5, arr[n];
calFac(n);
2020-04-15 12:28:20 +08:00
for (int i = 0; i < 5; ++i)arr[i] = i;
for (int i = 0; i < fac[n]; ++i) {
printArr(arr, n);
permute(arr, n, i);
}
2020-04-15 12:28:20 +08:00
return 0;
}