Server Time: Sat Sep 21, 2019 1:57 pm
Welcome ( logout
1060 - nth Permutation
  PDF (English) Statistics Forum
Time Limit: 2 second(s) Memory Limit: 32 MB

Given a string of characters, we can permute the individual characters to make new strings. At first we order the string into alphabetical order. Then we start permuting it.

For example the string 'abba' gives rise to the following 6 distinct permutations in alphabetical order.

aabb 1

abab 2

abba 3

baab 4

baba 5

bbaa 6

Given a string, you have to find the nth permutation for that string. For the above case 'aabb' is the 1st and 'baab' is the 4th permutation.


Input starts with an integer T (≤ 200), denoting the number of test cases.

Each case contains a non empty string of lowercase letters with length no more than 20 and an integer n (0 < n < 231).


For each case, output the case number and the nth permutation. If the nth permutation doesn't exist print 'Impossible'.

Sample Input

Output for Sample Input


aabb 1

aabb 6

aabb 7

Case 1: aabb

Case 2: bbaa

Case 3: Impossible


Problem Setter: Jane Alam Jan
Developed and Maintained by
Copyright © 2012
LightOJ, Jane Alam Jan