nth Permutation / LightOJ - 1060
Given a string of characters, we can permute the individual characters to make new strings. At first we order the string into alphabetical order. Then we start permuting it.
For example the string 'abba' gives rise to the following 6 distinct permutations in alphabetical order.
aabb 1
abab 2
abba 3
baab 4
baba 5
bbaa 6
Given a string, you have to find the nth permutation for that string. For the above case 'aabb' is the 1st and 'baab' is the 4th permutation.
Input
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case contains a non empty string of lowercase letters with length no more than 20 and an integer n (0 < n < 2^31).
Output
For each case, output the case number and the nth permutation. If the nth permutation doesn't exist print 'Impossible'.
Sample Input
3
aabb 1
aabb 6
aabb 7
Sample Output
Case 1: aabb
Case 2: bbaa
Case 3: Impossible
题意
给你一个串, 让你求这个串的第n种组合
题解
康托展开
具体看注释
代码
#include<bits/stdc++.h>
using namespace std;
char s[31];
long long f[31];
int T, n, num[31], Case = 1;
int main(){
f[0] = f[1] = 1;
for(int i = 2; i <= 20; i++){//求i的阶乘
f[i] = f[i - 1] * i;
//实质上求有i个不相等的数时 有多少种组合方案
}
scanf("%d", &T);
while(T--){
scanf("%s%d", s, &n);
memset(num, 0, sizeof(num));
int len = strlen(s);
for(int i = 0; i < len; i++){
num[s[i] - 'a']++;//这种字母有几个
}
long long maxn = f[len];//目前这个串最多有多少种组合方案
for(int i = 0; i < 26; i++){
if(num[i]){
maxn /= f[num[i]];//因为可能会有重复的元素 所以要除掉
}
}
printf("Case %d: ", Case++);
if(maxn < n){//没有第n种方案
printf("Impossible\n");
continue;
}
for(int i = 0; i < len; i++){//枚举每一位
for(int j = 0; j < 26; j++){//枚举第j种字母
if(!num[j]){//没有这种字母或者已经全搜过走
continue;
}
num[j]--;//假设第i为上放第j种字母
long long mx = f[len - i - 1];//当前位置最多多少种组合方案
for(int k = 0; k < 26; k++){
if(num[k]){
mx /= f[num[k]];//排除重复元素的方案
}
}
if(mx >= n){
putchar(j + 'a');
break;
}
n -= mx;//减掉这种组合数, 反过来想想 第j个不行 那么下一个也肯定不行
//因为要找第n种, 第j个字母是mx种, 那么下一种就是在这个mx的基础上再加, 所以要减去
num[j]++;//回溯回去啦
}
if(i == len - 1){
printf("\n");
}
}
}
return 0;
}
PS
num[]数组必须开到26以上
每次while循环, num初始化一下
没有未来的未来不是我想要的未来

浙公网安备 33010602011771号