UVALive6814 Lexicography

An anagram of a string is any string that can be formedusing the same letters as the original. (We consider the original string ananagram of itself as well.) For example, the stringACM has thefollowing 6 anagrams, as given in alphabetical order:

ACMAMCCAMCMAMACMCA

As another example, the string ICPC has the following 12anagrams (in alphabetical order):

CCIPCCPICICPCIPCCPCICPICICCPICPCIPCCPCCIPCICPICC

Given a string and a rank K, you are to determinethe Kth such anagram according to alphabetical order.

Input: Each test case willbe designated on a single line containing the original word followed by thedesired rankK. Words will use uppercase letters (i.e., A through Z) and willhave length at most 16. The value ofK will be in the range from 1 tothe number of distinct anagrams of the given word. A line of the form "# 0"designates the end of the input.

Warning: The value of Kcould be almost 245 in the largest tests, so you should use typelong in Java,or type long long in C++ to store K.

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

Example Input:

Example Output:

ACM 5ICPC 12REGION 274# 0

MACPICCIGNORE

#include <stdio.h>#include <iostream>#include <cmath>#include <string>#include <cstring>#include <algorithm>#define ll long long#define N 50using namespace std;char str[N];ll k;int num[N];ll f[N];ll fun(int x){ll ans=f[x];for(int i=0;i<26;i++)ans/=f[num[i]];//除以相同个数的阶乘return ans;}void solve(int len){for(int i=0;i<len;i++){for(int j=0;j<26;j++){if(num[j]){num[j]–;//当前被占用了一个ll a=fun(len-i-1);num[j]++;if(a>=k){num[j]–;printf("%c",'A'+j);break;}elsek-=a;}}}cout<<endl;}int main(){f[0]=1;for(int i=1;i<=17;i++)//阶乘f[i]=f[i-1]*i;while(~scanf("%s %lld",str,&k)){if(k==0) break;int len=strlen(str);memset(num,0,sizeof num);for(int i=0;i<len;i++){num[str[i]-'A']++;}solve(len);}return 0;}

,想念我的时候,不要忘记我也在想念你。

UVALive6814 Lexicography

相关文章:

你感兴趣的文章:

标签云: