
You are given an N x M matrix ‘MAT’ and an integer ‘K’. All rows in the matrix have values in sorted order. You can choose 1 integer from each row and make an array of length ‘N’. Your task is to find the smallest k-th smallest array sum out of all the possibilities.
The first line of the input contains ‘T’ denoting the number of test cases.
In the first line of each test case take three space-separated integers, ‘N’, ‘M’, and ‘K’.
Next N lines contains M space-separated integers MAT[i][j], denoting value stored in position (i, j) in matrix.
Output Format:
For each test case, print a single line containing a single integer denoting the k-th smallest array sum.
The output for every test case will be printed in a separate line.
Note:
You don’t need to print anything; It has already been taken care of. Just implement the function.
1 <= T <= 5
1 <= N, M <= 100
1 <= K <= min(100,N ^ 2)
0 <= MAT[ i ][ j ] <= 2000
MAT[ i ][ j ] <= MAT[ i ][ j + 1 ]
Time Limit: 1 sec.
2
2 3 1
1 2 3
4 5 6
2 3 4
1 2 3
4 5 6
5
7
All possible sums in ascending order are:
[ 1 + 4, 1 + 5, 2 + 4, 1+6, 2 + 5, 3 + 4, 2 + 6, 3 + 5, 3 + 6 ]
Sums = [5, 6, 6, 7, 7, 7, 8, 8, 9]
In test case 1:
Ans = sums[1] = 5
In test case 2:
Ans = sums[4] = 7
2
5 5 20
5 6 10 17 29
8 14 14 21 24
2 4 23 24 29
3 4 11 18 24
0 6 6 15 21
4 4 11
0 7 7 14
1 1 7 15
0 15 18 28
18 19 24 30
25
26
Find the K'th smallest sums for each row.
O(N * M * K), where N, M, and K are as described in the problem.
From every cell in the matrix, we are calculating sums by using K smallest sums till the last row, which makes complexity O(N * M * K)
O(M * K), where M and K are as described in the problem.
The size of the ‘cur’ array can go up to M * K, as total sums in the current row can be (K sums from the previous row) * (M possibilities from current row) i.e. O(M * K)