lightoj 1060 - nth Permutation(逆康拓展开)

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<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 1e9
#define endl '\n'
#define mod 100000007
#define LL long long

using namespace std;

LL f[30];
int num[30];

LL kangtuo(int n)
{
    LL ans = f[n];
    for(int i=0;i<26;i++)
        ans /= f[num[i]];
    return ans;
}
int main(void)
{
    int T,n,i,j;
    LL k;
    char a[30];
    scanf("%d",&T);
    f[0] = 1;
    for(i=1;i<=20;i++)
        f[i] = f[i-1]*i;
    int cas = 1;
    while(T--)
    {
        scanf("%s%lld",a,&k);
        n = strlen(a);
        memset(num,0,sizeof(num));
        for(i=0;i<n;i++)
            num[a[i]-'a']++;
        printf("Case %d: ",cas++);
        if(k > kangtuo(n))
        {
            printf("Impossible\n");
            continue;
        }
        for(i=1;i<=n;i++)
        {
            for(j=0;j<26;j++)
            {
                if(num[j] == 0)
                    continue;
                num[j]--;
                LL t = kangtuo(n-i);
                if(k > t)
                {
                    k -= t;
                    num[j]++;
                }
                else
                {
                    printf("%c",'a'+j);
                    break;
                }
            }
        }
        printf("\n");
    }

    return 0;
}


 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值