## FUNNUMS - FUN WITH LETTERS

Mr. Bean’s uncle gifted him 15 English letter toys from 'a' to 'o'. As Mr. Bean is a joker, no one was willing to play with him. So he sat on the floor and arranged these toys in ascending order i.e. “abcdefghijklmno”. Then he figured out the next greatest word in lexicographic order that can be formed by rearranging the toys is “abcdefghijklmon”. Now he is learning programming and wants to write a program to solve the following problem: Given all the words that can be formed by rearranging letters form the given word S, find the N-th greater word in lexicographic order. You can safely assume that such a word always exists.

Input Specification:

The first line contains a natural number T denoting the number of test cases. Next T lines contain the description of T test cases, each with string S and value N.

Output Specification:

For each test case print the answer in a separate line.

Input Constraints:

1<=t<=1000

2<=S.length()<=15

'a'<=S[i]<='a'+S.length()-1

All letters in S are unique.

Sample Input:

3

abdc 2

adcb 3

badc 7

Sample Output:

acdb

bcad

cbad

 Added by: cegprakash Date: 2013-02-24 Time limit: 2s Source limit: 50000B Memory limit: 1536MB Cluster: Cube (Intel G860) Languages: All except: ASM64 BF GOSU

hide comments
 2013-02-27 18:45:38 Po what is the range for 'n'? Reply: Already answered Last edit: 2013-02-27 18:51:16 2013-02-27 17:40:52 MITIANS what will be the output for this ? 1 ab 2 Reply: "You can safely assume that such a word always exists." So this input is also invalid Last edit: 2013-02-27 22:40:31 2013-02-27 17:11:01 chansiddharth can n be 15! ????? if such a permutation exist, then "YES" Last edit: 2013-02-27 17:22:40 2013-02-27 16:19:38 Gokul Must the string S be sorted and then checked for nth Greater string? Reply: No Last edit: 2013-02-27 16:41:09 2013-02-27 16:13:21 Ashwin. K is the output correct for the given sample? Is tit the lexigraphically next or just move the last element to the right? Reply: *lexicographically next! Last edit: 2013-02-27 16:41:47 2013-02-27 16:42:24 Jimmy Is it guaranteed that the symbols are first n letters of alphabet? Reply: Yes Last edit: 2013-02-27 16:42:35 2013-02-27 15:48:47 cegprakash "You can safely assume that such a word always exists." from this u can assume the value of n 2013-02-27 15:37:19 nikhil Input constraints for n?
© Spoj.com. All Rights Reserved. Spoj uses Sphere Engine™ © by Sphere Research Labs.