Time Limit: 2 second(s) | Memory Limit: 32 MB |
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 < 231).
Output
For each case, output the case number and the nth permutation. If the nth permutation doesn't exist print 'Impossible'.
Sample Input | Output for Sample Input |
3 aabb 1 aabb 6 aabb 7 | Case 1: aabb Case 2: bbaa Case 3: Impossible |
题意:给一个小写字母组成的字符串,求这个字符串字典序排序后的第k个字符串
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N = 1e6+7;
const int inf = 0x3f3f3f3f;
const int mod = 10007;
char str[30];
int num[30];
LL c[30][30];
LL judge(int n)
{
LL ans=1;
for(int i=0; i<26; i++)
{
if(!num[i]) continue;
ans*=c[n][num[i]];
n-=num[i];
}
return ans;
}
int main()
{
memset(c,0,sizeof(c));
for(int i=0; i<=27; i++) c[i][0]=c[i][i]=1;
for(int i=2; i<=27; i++)
for(int j=1; j<i; j++)
c[i][j]=c[i-1][j]+c[i-1][j-1];
int ncase=1, t;
LL n;
scanf("%d", &t);
while(t--)
{
scanf("%s %lld",str, &n);
printf("Case %d: ",ncase++);
memset(num,0,sizeof(num));
int len=strlen(str);
for(int i=0; str[i]; i++) num[str[i]-'a']++;
if(judge(len)<n) puts("Impossible");
else
{
for(int i=1; i<=len; i++)
{
for(int j=0; j<26; j++)
{
if(!num[j]) continue;
num[j]-=1;
LL tmp=judge(len-i);
if(tmp>=n)
{
printf("%c",j+'a');
break;
}
num[j]+=1;
n-=tmp;
}
}
cout<<endl;
}
}
return 0;
}