You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

34 lines
853 B

#include <bits/stdc++.h>
using namespace std;
int fact[20];
void init_fact(int n) {
fact[0] = 1; // 0的阶乘为1
for (int i = 1; i <= n; i++) fact[i] = fact[i - 1] * i;
}
string ans;
// 逆康托展开
void getPermutation(int n, int k) {
vector<char> v; // 存放当前可选数,有序
for (int i = 1; i <= n; i++) v.push_back(i + '0');
k--; // 要先 -1 才是其康托展开的值
for (int i = n; i; i--) {
int r = k % fact[i - 1];
int t = k / fact[i - 1];
k = r;
ans += v[t]; // 剩余数里第t+1个数为当前位
v.erase(v.begin() + t); // 移除选做当前位的数
}
}
int main() {
int n = 5, k = 107; // 107
init_fact(10); // 预处理阶乘
getPermutation(n, k);
cout << ans << endl;
return 0;
}