no tags 

       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:





All letters in S are unique.


Sample Input:


abdc 2

adcb 3

badc 7

Sample Output:




hide comments
Akshat Mathur: 2015-08-05 16:56:41

Finally AC :-)

Saurabh_P: 2013-12-25 23:53:02

getting tle.... dont get it

Abhinav: 2013-12-17 12:57:29

use long long int ...I got 4 WAs bcoz of that

Kartik Khare: 2013-12-17 12:57:29

just can't figure out why am i getting wrong answer.

BLANKRK: 2013-12-17 12:57:29

m gettin tle again n again.... whts the problm

Aradhya: 2013-12-17 12:57:29

50th user \m/

Aradhya: 2013-12-17 12:57:29

ohh my god.... got loads of wrong answers just because of a silly mistake :P :P.. btw awesome problem ;)

Federico Lebrón: 2013-12-17 12:57:29

I'm not sure I follow. If I have the letters abdc, of all the possible permutations of those letters, the 2nd greatest one lexicographically is dcab (the largest is dcba). Why is the correct answer acdb? And why does it matter that the input is permuted? The lexicographical permutations will be the same (as will their order), regardless of the initial permutation of S.
--ans(francky)--> It's "largest" compared to the given one in input.
Ah, alright, I understand (and AC, after a dumb mistake) then :). I would word it as "the Nth larger word", not largest, but I guess with this comment it's enough to clarify :) Thanks!

Last edit: 2013-05-01 20:20:21
Francky: 2013-12-17 12:57:29

@Runtime error : description says "You can safely assume that such a word always exists.", so you should be able to determine by yourself the maximum n. I think it's part of the problem.

Runtime Error: 2013-12-17 12:57:29

how big is n?

Added by:cegprakash
Time limit:2s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64