hdoj-1027-Ignatius and the Princess II(逆康拓展开)
1 /* 2 Name: 3 Copyright: 4 Author: 5 Date: 2018/5/2 11:07:16 6 Description:输出第m小的序列 7 */ 8 #include <iostream> 9 #include <cstdio> 10 #include <vector> 11 #include <algorithm> 12 #include <cstring> 13 using namespace std; 14 int fac[] = {1,1,2,6,24,120,720,5040,40320};//阶乘 15 //康托展开的逆运算,{1...n}的全排列,中的第k个数为s[] 16 void reverse_kangtuo(int n,int k,int s[]) 17 { 18 int i, j, t, vst[1001]={0}; 19 --k; 20 for (i=0; i<n; i++) 21 { 22 if (n-i-1 > 8) { 23 t = k/fac[8]; 24 } else { 25 t = k/fac[n-i-1]; 26 } 27 for (j=1; j<=n; j++) 28 if (!vst[j]) 29 { 30 if (t == 0) break; 31 --t; 32 } 33 s[i] = j; 34 vst[j] = 1; 35 if (n-i-1 > 8) { 36 k %= fac[8]; 37 } else { 38 k %= fac[n-i-1]; 39 } 40 } 41 } 42 43 int main() 44 { 45 int s[1005] ; 46 int m, n; 47 while (cin>>m>>n) { 48 memset(s, 0, sizeof(s)) ; 49 reverse_kangtuo(m, n, s); 50 cout<<s[0]; 51 for (int i=1; i<m; i++) { 52 cout<<" "<<s[i]; 53 } 54 cout<<endl; 55 } 56 return 0; 57 }