| 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 |
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
#define bug printf("hihi\n")
#define eps 1e-8
typedef long long ll;
using namespace std;
#define N 22
long long p[N];
int vis[30];
void inint()
{
p[0]=1;
for(int i=1;i<N;i++)
p[i]=p[i-1]*i;
}
void dfs(int len,ll pos)
{
if(len==0) return ;
int i;
ll temp=p[len-1];
for(i=0;i<26;i++)
{
if(vis[i]==0) continue;
ll ha=temp;
for(int j=0;j<26;j++)
{
if(j==i) ha/=p[vis[i]-1];
else ha/=p[vis[j]];
}
if(ha<pos) {
pos-=ha;
continue;
}
printf("%c",i+'a');
vis[i]--;
dfs(len-1,pos);
}
}
int main()
{
inint();
int i,j,t,ca=0;
long long pos;
scanf("%d",&t);
char c[N];
while(t--)
{
scanf("%s%lld",c,&pos);
memset(vis,0,sizeof(vis));
int len=strlen(c);
for(int i=0;i<len;i++)
vis[c[i]-'a']++;
ll temp=p[len];
for(int i=0;i<26;i++)
temp/=p[vis[i]];
if(temp<pos)
{
printf("Case %d: Impossible\n",++ca);
continue;
}
//printf("temp=%lld\n",temp);
printf("Case %d: ",++ca);
dfs(len,pos);
printf("\n");
}
return 0;
}
本文介绍了一种算法,用于解决给定字符串后找到其字典序中的第N个排列的问题。通过递归分解和数学组合的方法,在限定的时间和空间复杂度内高效地找出目标排列。


被折叠的 条评论
为什么被折叠?



