#P10644. Constructing a Matrix from Absolute Differences

    ID: 12671 Type: Default 1000ms 256MiB

Constructing a Matrix from Absolute Differences

Constructing a Matrix from Absolute Differences

In this problem, we are given a grid of size N×MN\times M representing a city. Each cell (i,j)(i,j) has an unknown electricity consumption value Ai,jA_{i,j}, which can be positive, negative, or zero. For each cell, we define [ C_{i,j} = \left|\sum_{k=1}^N A_{k,j} - \sum_{k=1}^M A_{i,k}\right|. ]

In other words, for every cell the absolute difference between the total consumption of its column and the total consumption of its row is given. You are provided with all values of Ci,jC_{i,j} and need to determine a valid construction of the matrix AA. It is guaranteed that there is at least one solution.

A hint on our approach: define the row sums as Xi=k=1MAi,kX_i=\sum_{k=1}^M A_{i,k} and the column sums as Yj=k=1NAk,jY_j=\sum_{k=1}^N A_{k,j}. Then for every i,ji,j we have [ |Y_j - X_i| = C_{i,j}. ] We can choose X1=0X_1=0 and set Yj=C1,jY_j=C_{1,j} for j=1,,Mj=1,\dots,M. For each i2i\ge2, cell (i,1)(i,1) gives [ |C_{1,1} - X_i| = C_{i,1}, ] which implies two possible candidates for XiX_i: either Xi=C1,1Ci,1X_i=C_{1,1}-C_{i,1} or Xi=C1,1+Ci,1X_i=C_{1,1}+C_{i,1}. Choose the candidate that satisfies (|C_{1,j}-X_i|=C_{i,j}) for all j=1,,Mj=1,\dots,M.

Once XX and YY are determined (note that they satisfy (\sum_{i=1}^N X_i = \sum_{j=1}^M Y_j)), a valid matrix AA can be constructed as follows:

For the first row, set [ A_{1,1} = X_1 - \sum_{j=2}^M Y_j, \quad A_{1,j} = Y_j \quad (j\ge2). ] For each row i2i\ge2, set [ A_{i,1} = X_i, \quad A_{i,j} = 0 \quad (j\ge2). ]

This construction guarantees that the row sums of AA are XiX_i and the column sums are YjY_j, thereby satisfying the conditions.

Your task is to implement this solution. The input starts with two integers NN and MM, followed by the N×MN\times M grid CC. The output should be the constructed matrix AA, printed as NN lines with MM space‐separated integers on each line.

inputFormat

The first line contains two integers NN and MM. Then follow NN lines, each containing MM integers where the jj-th integer in the ii-th line is Ci,jC_{i,j}.

outputFormat

Output NN lines, each containing MM space-separated integers representing the matrix AA that satisfies the given conditions.

sample

2 2
4 3
3 4
-3 3

7 0

</p>