#P6070. Minimum Operations to Zero Matrix
Minimum Operations to Zero Matrix
Minimum Operations to Zero Matrix
Given an matrix, initially with all zeros except for cells which contain non-zero integers, you are allowed to perform the following operation any number of times:
In one operation, you can choose any contiguous submatrix and either add to all its cells or subtract from all its cells.
Determine the minimum number of operations required to turn the entire matrix into zeros. If it is impossible, output -1.
Note: The matrix indices are 1-indexed, and only positions are non-zero initially, with their values provided. The remaining positions contain .
inputFormat
The first line contains three integers , , and , where is the size of the matrix, is the size of the submatrix for each operation, and is the number of cells with nonzero values.
Each of the next lines contains three integers , , and , representing that the cell at row and column has the initial value . It is guaranteed that the rest of the matrix cells are .
It is guaranteed that .
outputFormat
Output a single integer: the minimum number of operations required to make the matrix all zeros, or -1 if it is impossible.
sample
4 2 7
1 1 3
1 2 3
2 1 3
2 2 1
2 3 -2
3 2 -2
3 3 -2
5