Time Limit: 1000MS | Memory Limit: 131072KB | 64bit IO Format: %lld & %llu |
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.
题意:给定一个串和k,求这个串字典序第k的序列。
代码;
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <string>
#include <map>
#include <stack>
#include <vector>
#include <set>
#include <queue>
#pragma comment (linker,"/STACK:102400000,102400000")
#define maxn 1005
#define MAXN 2005
#define mod 1000000009
#define INF 0x3f3f3f3f
#define pi acos(-1.0)
#define eps 1e-6
#define lson rt<<1,l,mid
#define rson rt<<1|1,mid+1,r
#define FRE(i,a,b) for(i = a; i <= b; i++)
#define FREE(i,a,b) for(i = a; i >= b; i--)
#define FRL(i,a,b) for(i = a; i < b; i++)
#define FRLL(i,a,b) for(i = a; i > b; i--)
#define mem(t, v) memset ((t) , v, sizeof(t))
#define sf(n) scanf("%d", &n)
#define sff(a,b) scanf("%d %d", &a, &b)
#define sfff(a,b,c) scanf("%d %d %d", &a, &b, &c)
#define pf printf
#define DBG pf("Hi\n")
typedef long long ll;
using namespace std;
ll fac[20],k;
char str[30];
int num[30];
ll getnum(int l)
{
ll s=fac[l];
for (int i=0;i<26;i++)
s/=fac[num[i]];
return s;
}
void solve(int len)
{
for (int i=0;i<len;i++)
{
for (int j=0;j<26;j++)
{
if (num[j])
{
num[j]--;
ll x=getnum(len-i-1);
num[j]++;
if (x>=k)
{
num[j]--;
printf("%c",j+'A');
break;
}
else k-=x;
}
}
}
printf("\n");
}
int main()
{
// freopen("C:/Users/asus1/Desktop/IN.txt","r",stdin);
int i,j;
fac[0]=1;
for (i=1;i<=17;i++)
fac[i]=fac[i-1]*i;
while (scanf("%s %lld",str,&k))
{
if (k==0) break;
int len=strlen(str);
mem(num,0);
for (i=0;i<len;i++)
num[str[i]-'A']++;
solve(len);
}
return 0;
}