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
明显的求全排列的第几个,我们可以用阶乘的方法来确定每一位该放什么字母
#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; #define ls 2*i #define rs 2*i+1 #define up(i,x,y) for(i=x;i<=y;i++) #define down(i,x,y) for(i=x;i>=y;i--) #define mem(a,x) memset(a,x,sizeof(a)) #define w(a) while(a) #define LL long long const double pi = acos(-1.0); #define Len 100005 char str[50],ans[50]; LL f[50],m; int main() { int i,j,k,len1,len2,cnt[50]; f[0] = 1; up(i,1,16) f[i]=f[i-1]*i; w(~scanf("%s%lld",str,&m)) { if(str[0]=='#'&&m==0) break; mem(cnt,0); len1 = strlen(str); sort(str,str+len1); up(i,0,len1-1) cnt[str[i]-'A']++; up(i,0,len1-1) { LL last = 0,res; up(j,0,25) { if(cnt[j]) { res = f[len1-i-1]; up(k,0,25) { if(k==j) res/=f[cnt[k]-1]; else res/=f[cnt[k]]; } if(last+res>=m) { ans[i] = j+'A'; m-=last; cnt[j]--; break; } else last+=res; } } } ans[len1]='\0'; puts(ans); } return 0; }