CSU 1563 Lexicography (搜尋+組合數)

Mr_Treeeee發表於2020-04-06

1563: Lexicography

         Time Limit: 1 Sec     Memory Limit: 128 Mb     Submitted: 469     Solved: 150    

Description

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.

題意:

給你幾個字母,可以得到它們的全排列,要字典序,然後問你第k個排列是什麼。


POINT:

1.給字母排個序。

2.假設第k個排列的第一個字母是s[0],那麼可以算出s[1]-s[l-1]有幾種可能,和k比較。

3.k小於等於這個數,就可以確定第一個字母是s[0],反之則繼續遍歷下去,再假設s[1]……,別忘記減k

4.確定第一個字母之後,刪掉它,重複1 2 3


#include <iostream>
#include <map>
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;
#define LL long long
int cnt[333];
int m;
char s[20];
int ans[20];
LL jie[20],k;
void init()
{
    jie[0]=1;
    for(int i=1;i<=16;i++)
    {
        jie[i]=jie[i-1]*i;
    }
}
LL sum(int l)
{
    LL anss=jie[l];
    for(int i='A';i<='Z';i++)
    {
        anss/=jie[cnt[i]];
    }
    return anss;
}
void dfs(int now)
{
    if(now==m) return;
    for(int i=0;i<m-now;i++)
    {
        if(s[i]==s[i-1]) continue;
        cnt[s[i]]--;
        LL p=sum(m-now-1);
        if(k<=p)
        {
            ans[now]=s[i];
            s[i]='Z'+11;
            sort(s,s+m);
            dfs(now+1);
            break;
        }
        else
        {
            cnt[s[i]]++;
            k-=p;
        }
    }
    
}
int main()
{
    init();
    while(~scanf("%s %lld",s,&k))
    {
        if(s[0]=='#') break;
        memset(cnt,0,sizeof cnt);
        memset(ans,0,sizeof ans);
        m=strlen(s);
        for(int i=0;i<m;i++)
        {
            cnt[s[i]]++;
        }
        sort(s,s+m);
        dfs(0);
        for(int i=0;i<m;i++)
        {
            printf("%c",ans[i]);
        }
        printf("\n");
    }
}


相關文章