CSU1563 combination mathematics and csu1563 combination mathematics
C-Lexicography
Time Limit:1000 MS
Memory Limit:131072KB
64bit IO Format:% Lld & % maid Status Practice CSU 1563
Description
An ansible of a string is any string that can be formed using the same letters as the original. (We consider the original string an anal 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 anw.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 anal of the original string.
Sample Input
ACM 5ICPC 12REGION 274# 0
Sample Output
MACPICCIGNORE
Hint
The value of K cocould be almost 245 in the largest tests, so you shoshould use type long in Java, or type long in C ++ to store K.
Returns the k-th permutation of a string. If the first character is determined to be x, and the number of tots whose first character is less than x is calculated, the original problem is to calculate the k-tot arrangement whose first character is x, this is the last character.
# Include <iostream> # include <cstdio> # include <cstring> # include <vector> # include <queue> # include <algorithm> using namespace std; typedef long ll; # define rep (I, a, B) for (int I = (a); I <(B); ++ I) ll f [20]; int main (int argc, char const * argv []) {f [0] = 1; rep (I,) f [I] = f [I-1] * I; char s [20]; long m; while (~ Scanf ("% s % lld", s, & m) {if (s [0] = '#'&&! M) return 0; int sz = strlen (s); int cnt [30]; memset (cnt, 0, sizeof cnt); rep (I, 0, sz) cnt [s [I]-'a'] ++; rep (I, 0, sz) {ll tot = 0; rep (j, 0, 26) if (cnt [j]) {ll t = f [sz-i-1];/* The number of multiple arrays starting with I + 'A' */rep (k) {if (k = j) t/= f [cnt [k]-1]; else t/= f [cnt [k];} if (tot + t> = m) {s [I] = j + 'a'; m-= tot; cnt [j] --; break ;} else tot + = t;/* The number of multiple queues with the first character less than or equal to j + 'A' */} puts (s);} return 0 ;}