Lexicography CSU - 1563

An anagram of a string is any string that can be formed using the same letters as the original. (We consider the original string an anagram of itself as well.) For example, the string ACM has the following 6 anagrams, as given in alphabetical order:

ACM
AMC
CAM
CMA
MAC
MCA
As another example, the string ICPC has the following 12 anagrams (in alphabetical order):

CCIP
CCPI
CICP
CIPC
CPCI
CPIC
ICCP
ICPC
IPCC
PCCI
PCIC
PICC
Given a string and a rank K, you are to determine the Kth such anagram according to alphabetical order.

Input
Each test case will be designated on a single line containing the original word followed by the desired rank K. Words will use uppercase letters (i.e., A through Z) and will have length at most 16. The value of K will be in the range from 1 to the number of distinct anagrams of the given word. A line of the form “# 0” designates the end of the input.

Output
For each test, display the Kth anagram of the original string.

Sample Input
ACM 5
ICPC 12
REGION 274
# 0
Sample Output
MAC
PICC
IGNORE
Hint
The value of K could be almost 245 in the largest tests, so you should use type long in Java, or type long long in C++ to store K.

上來一看就是一道排列組合的問題,公式和容斥原理自然不必多說,注意看省略掉的細節就好。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>  
using namespace std;
// 不要小瞧人生啊
// 一道組合數學的字符串問題,需要用容斥原理解決
typedef long long ll;
char a[50], cnew[50];
ll vis[50], f[50] = { 0 };
int main() 
{
    int i, j, l, len, tlen = 0;
    f[0] = 1;
    for (i = 1; i <= 16; i++) //不會爆
    {
        f[i] = f[i - 1] * i;
    }
    ll k;
    while (~scanf("%s%lld", a, &k)) 
    {
        len = strlen(a);
        if (len == 1 && a[0] == '#'&&k == 0) break;
        memset(vis, 0, sizeof(vis));
        for (i = 0; i<len; i++) 
        {
            vis[a[i] - 'A']++;
        }
        sort(a, a + len);
        for (i = 0; i<len; i++) 
        {

            ll last = 0;
            for (j = 0; j<26; j++) 
            {

                if (vis[j]) 
                {

                    ll ans = f[len - 1 - i];
                    for (l = 0; l<26; l++) 
                    {
                        if (l == j) ans = ans / f[vis[l] - 1];
                        else ans = ans / f[vis[l]];
                    }

                    if (last + ans >= k) 
                    {
                        cnew[i] = j + 'A';
                        k = k - last;
                        vis[j]--;
                        break;
                    }
                    else last += ans;
                }
            }
        }
        cnew[len] = '\0';
        printf("%s\n", cnew);

    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值