Rectangle of Permutation

We want to build a rectangle where each row is a permutation of 0 to N-1. We want to make this rectangle with as many rows as possible while maintaining the following constraints. N−1 ∑∑ Di,j − Ci,j 0 when Di,j > Ci,j when Di,j ≤ Ci,j j=0 Ei,j ≤ Ai and Ei,j ≤ Bi, where Ei,j = N−1 j=0 { Di,j is the number of occurrences of integer j in the column i. C is a matrix of N rows and N columns will be given as input. A and B are two sequences of size N will be given as input. Given N, A, B, C build a rectangle with the largest possible number of rows. Input First line of the input contains T (1 ≤ T ≤ 50) the number of test cases. It is followed by T test cases. Each test case starts with an integer N (1 ≤ N ≤ 30) indicating the number of columns in the rectangle. Next line contains N integers separated by single spaces. These integers are A0 to AN−1 (0 ≤ Ai ≤ 10). Next line contains N integers separated by single spaces. These integers are B0 to BN−1 (0 ≤ Bi ≤ 10). Each of the next N line contains N integers in each line. The integer on row i and column j is Ci,j (0 ≤ Ci,j ≤ 4) (i and j starts from zero). A blank line will follow each test case. Output For each test case the first line of the output will be in the following format ‘Case #C: R’. Quotes are for clarity only. C is the test case number starting from 1. R is the maximum possible rows of the rectangle. Each of the next R lines should contain N integer in each line separated by spaces. Each of these N integers in each line should be a permutation of 0 to N − 1. The whole R × N rectangle should maintain the constraints as described in the problem statement. Sample Input 2 3 000 000 200 020 002 3 123 321 123 231 312

2/2 Sample Output Case 1: 2 012 012 Case 2: 7 012 102 102 210 210 210 021