Time Limit: 1 Sec Memory Limit:
128 MB
Submit: 162 Solved: 52
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.
Source
如何求出一个可以有重复字符的字符集的第k大字符串呢?
为了方便描述,我们规定最小的那个串是第一个串,
首先知道这些知识,
多重集:是集合概念的推广,在一个集合中,相同的元素只能出现一次,
在多重集之中,同一个元素可以出现多次。
假设字符共有n类,个数分别为m1,m2……,mn,
那么这个多重集的全排列个数为(m1+m2+……+mn)!/m1!/m2!/……/mn!
然后呢,我们来举个例子,要知道字符集"ICPC"的第12个字符串是多少,
对第一位做出假设
C的话,那么有3!=6种串,
I的话,有3!/2!=3种串,
P的话,有3!/2!=3种串,
可知6+3+3=12,那么第一位就是P,从剩下的字符集里找出第12-6-3=3个字符串
现在字符集变成"ICC",
对第二位做出假设
C的话,那么有2!=2种串,
I的话,有2!/2!=1种串,
可知2+1=3,所以,第二位就是I,从剩下的字符集里找出第3-2=1个字符串
现在字符集变成"CC",
对第三位做出架设
C的话,那么有1!=1种串,
可知1=1,于是,第三位就是C,从剩下的字符集里找出第1-1=0个字符串,
现在字符集变成”C",
这个串并不存在,那么就是直接把剩下的那些字符,就是C补在最后就行了,
很显然,此时剩下的字符集一定都是由某个字符重复组成。
#include<map> #include<string> #include<cstring> #include<cstdio> #include<cstdlib> #include<cmath> #include<queue> #include<vector> #include<iostream> #include<algorithm> #include<bitset> #include<climits> #include<list> #include<iomanip> #include<stack> #include<set> using namespace std; typedef long long ll; ll fac[20]; void create() { fac[0]=1; for(ll i=1;i<=16;i++) fac[i]=i*fac[i-1]; } string work(string s,ll k) { map<int,int>num; for(int i=0;i<s.length();i++) num[s[i]-'A']++; int len=s.length(); s.clear(); while(num.size()) { len--; ll sum=0; for(map<int,int>::iterator it=num.begin();it!=num.end();it++) { ll t=fac[len]/fac[it->second-1]; for(map<int,int>::iterator jt=num.begin();jt!=num.end();jt++) if(it!=jt) t/=fac[jt->second]; if(sum+t>=k) { s+=char(it->first+'A'); it->second--; if(it->second==0) num.erase(it); k-=sum; break; } sum+=t; } } return s; } int main() { create(); string s; ll k; while(cin>>s>>k) { if(s=="#"&&k==0) return 0; cout<<work(s,k)<<endl; } }