I have NxM matrix with integer elements, greater or equal than 0.
From any cell I can transfer 1 to another one (-1 to the source cell, +1 to the destination).
Using this operation, I have to make sums for all rows and columns equal. The question is how to find the minimal amount of such operations to achieve my task. During the processing cells may be negative.
For example, for
1 1 2 2
1 0 1 1
0 0 1 1
1 1 1 2
The answer is 3.
P.s.: I’ve tried to solve it on my own, but came only to brute-force solution.
Let us consider the one dimensional case: you have an array of numbers and you are allowed a single operation: take 1 from the value of one of the elements of the array and add it to other element. The goal is to make all elements equal with minimal operations. Here the solution is simple: you choose random “too big number” and add one to random “too small” number. Let me now describe how this relates to the problem at hand.
You can easily calculate the sum that is needed for every column and every row. This is the total sum of all elements in the matrix divided by the number of columns or rows respectively. From then on you can calculate which rows and columns need to be reduced and which – increased. see here:
So now we generate two arrays: the array of displacements in the rows:
-2,+1,+2,-1and the number of displacements in the columns:+1,+2,-1,-2. For this two arrays we solve the simpler task described above. It is obvious that we can not solve the initial problem in fewer steps than the ones required for the simpler task (otherwise the balance in the columns or rows will not be 0).However I will prove that the initial task can be solved in exactly as many steps as is the maximum of steps needed to solve the task for the columns and rows:
Every step in the simpler task generates two indices
iandj: the index from which to subtract and the index to which to add. Lets assume in a step in the column task we have indicesciandcjand in the row task we have indicesriandrj. Then we assign a correspondence of this in the initial task: take 1 from(ci, ri)and add one to(cj, rj). At certain point we will reach a situation in which there might be still more steps in, say, the columns task and no more in the rows task. So we getciandcj, but what do we do forriandrj? We just chooseri=rjso that we do not screw up the row calculations.In this solution I am making use of the fact I am allow to obtain negative numbers in the matrix.
Now lets demonstrate: