当前位置: 代码迷 >> 综合 >> CSU 1563 Lexicography(计算可重集的第k个数)
  详细解决方案

CSU 1563 Lexicography(计算可重集的第k个数)

热度:11   发布时间:2023-11-15 17:01:49.0
CSU1563:Lexicography(数学)

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.

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stack>
#include <queue>
#include <map>
#include <set>
#include <vector>
#include <math.h>
#include <algorithm>
using namespace std;
const double pi = acos(-1.0);
#define Len 100005char str[50],ans[50];
long long  f[50],m;
/*
代码非原创:
打表阶乘,该算法最核心的部分是对于k,
如果后面的阶乘数小于k,则当前位不变,
如果大于等于k,则要用last记忆计算出的res,
直至last+res>=k,则对于遍历到的i,
记录答案,更新计数数组和m.
*/int main()
{int i,j,k,len1,len2,cnt[50];f[0] = 1;for(int i=1;i<=16;i++)f[i]=f[i-1]*i;while(~scanf("%s%lld",str,&m)){if(str[0]=='#'&&m==0)break;memset(cnt,0,sizeof(mem));len1 = strlen(str);sort(str,str+len1);for(int i=0,i<=len1-1;i++)cnt[str[i]-'A']++;for(int i=0;i<=len-1;i++){long long last=0,res;for(int j=0;j<26;j++){if(!cnt[j]) continue;res=f[len-i-1];for(int k=0;k<26;k++){if(j==k) res/=f[cnt[k]-1];else res/=f[cnt[k]];}//去重if(last+res>=m){ans[i]='A'+j;m-=last;cnt[j]--;break;}elselast+=res;}}ans[len1]='\0';puts(ans);}return 0;
}