CSU 1563 Lexicography (搜索+组合数)

来源:互联网 发布:选购笔记本 知乎 编辑:程序博客网 时间:2024/06/13 06:23

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 5ICPC 12REGION 274# 0

Sample Output

MACPICCIGNORE

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 longint 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");    }}


原创粉丝点击