Hamming Base

You are given N integers in base-N each of them having exactly M digits (may be with some leading zeros). Two integers are called K-similar if they have the same digits in exactly K positions. For example 321 and 213 are 0-similar. 3456 and 6453 are 2-similar, 123 and 453 are 1-similar. You want to change these given N-integers in such a way that each pair of these integers are 0-similar. To achieve this goal you can change the integers in several steps. In a single step you can change a single digit of a single integer by 1 (incrementing or decrementing). But you can’t decrement if the digit is 0 or you can’t increment if the digit is N − 1. You need to achieve your goal in minimum number of steps. Input Input starts with an integer T (≤ 50), denoting the number of test cases. Each case starts with a line containing two integers N (2 ≤ N ≤ 2000) and M (1 ≤ M ≤ 10). Each of the next N lines contains M integers between 0 and N − 1 inclusive. These M integers form an M digit number in base N. Output For each case, print the case number and the minimal steps required to achieve your goal. Sample Input 2 33 000 000 000 42 00 00 02 20 Sample Output Case 1: 9 Case 2: 8