1. 
/**
* FWP, Ausgewählte Probleme aus dem ACM Programming Contest, SS10
* Problem: 941 - Permutations
* Link: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=11&page=show_problem&problem=882
*
* @author Evgeni Pavlidis
* @version 1.0, 06/19/2010
*
* Method : BigInteger - Unranking of permuation
* Status : Accepted
* Runtime: 1.340
*/

import java.io.*;
import java.util.*;
import java.math.*;

class Main
{
public static void main(String...args) throws Exception
{
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringBuffer output = new StringBuffer();

int pos ,s, testCases = Integer.parseInt(reader.readLine());

BigInteger n;
BigInteger[] f = new BigInteger[20];


// precalc factorials
f[1] = n = BigInteger.ONE;
for(int i = 2; i < 20; i++)
f[i] = f[i-1].multiply(BigInteger.valueOf(i));


String input;
List<Character> list = new ArrayList<Character>();

for(int tc = 0; tc < testCases; tc++)
{
input = reader.readLine();
n = new BigInteger(reader.readLine());

list.clear();
for(int i = 0; i < input.length(); i++)
list.add(input.charAt(i));

Collections.sort(list);


// unrank permuation
for(int i = list.size()-1; i > 0; i--)
{
pos = n.divide(f[i]).intValue();
n = n.mod(f[i]);

output.append(list.get(pos));
list.remove(pos);
}

output.append(list.get(0));
output.append("\n");

}

System.out.print(output);
}
}