标签:
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.
ACM 5 ICPC 12 REGION 274 # 0
MAC PICC IGNORE
示例程序
#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; }
SDUT 3185 Lexicography(排列问题(不会))
标签:
原文地址:http://blog.csdn.net/yeguxin/article/details/45021833