Lexicography
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
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.
输入
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.
Warning: 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.
输出
For each test, display the Kth anagram
of the original string.
示例输入
ACM 5 ICPC 12 REGION 274 # 0
示例输出
MAC PICC IGNORE
提示
来源
2014 ACM MId-Central Reginal Programming Contest(MCPC2014)
示例程序
#include<cstring> #include<cstdio> #include<iostream> #include<algorithm> #include<map> #define LL long long using namespace std; LL a[20]; void init() { int i; a[0]=1; for(i=1;i<=17;i++) { a[i]=a[i-1]*i; } } string se(string str,LL n) { int i; string s; map<int,int>st; int l=str.length(); for(i=0;i<=l-1;i++) { st[str[i]-'A']++; } while(st.size()) { l--; LL sum=0; for(map<int,int>::iterator it=st.begin();it!=st.end();it++) { LL ans=a[l]/a[it->second-1]; for(map<int,int>::iterator j=st.begin();j!=st.end();j++) { if(it!=j) { ans=ans/a[j->second]; } } if(sum+ans>=n) { s+=char(it->first+'A'); it->second--; if(it->second==0) { st.erase(it); } n=n-sum; break; } sum+=ans; } } return s; } int main() { init(); string str; LL n; while(cin>>str>>n) { if(str=="#"&&n==0) { break; } cout<<se(str,n)<<endl; } return 0; }