light oj 1060 - nth Permutation(组合数)@

1060 - nth Permutation
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;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值