//Earning Biggest Prize Money 2
import java.util.Scanner;
public class Solution {
static String input;
static int[] digits;
static int noExchange;
static int count;
static int max;
static void read(Scanner sc) {
input = sc.next();
digits = new int[input.length()];
for (int i = 0; i < digits.length; i++) {
digits[i] = (int) input.charAt(i) - '0';
}
noExchange = Integer.parseInt(sc.next());
count = 0;
max = 0;
}
static void swap(int i, int j) {
int t = digits[i];
digits[i] = digits[j];
digits[j] = t;
}
static int calculate() {
int factor = 1;
int result = 0;
for (int i = digits.length - 1; i >= 0; i--) {
result += digits[i] * factor;
factor *= 10;
}
return result;
}
static void permutation(int i) {
if (i == digits.length) {
if (count <= noExchange && (count - noExchange) % 2 == 0) {
int temp = calculate();
if (max < temp) {
max = temp;
}
}
return;
}
for (int j = i; j < digits.length; j++) {//với j=i => giữ nguyên i và đổi i+1, i+2 ...
swap(i, j);
if (i != j) //giữ nguyên i
count++;
permutation(i + 1);
swap(i, j);
if (i != j)//giữ nguyên i
count--;
}
}
public static void main(String[] args) {
// System.setIn(new FileInputStream("input/money.txt"));
Scanner sc = new Scanner(System.in);
int test = Integer.parseInt(sc.next());
for (int t = 1; t <= test; t++) {
read(sc);
permutation(0);
System.out.println("Case #" + t);
System.out.println(max);
}
sc.close();
}
}