#P6070. Minimum Operations to Zero Matrix

    ID: 19294 Type: Default 1000ms 256MiB

Minimum Operations to Zero Matrix

Minimum Operations to Zero Matrix

Given an n×nn \times n matrix, initially with all zeros except for mm 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 k×kk \times k contiguous submatrix and either add 11 to all its cells or subtract 11 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 mm positions are non-zero initially, with their values provided. The remaining positions contain 00.

inputFormat

The first line contains three integers nn, kk, and mm, where nn is the size of the matrix, kk is the size of the submatrix for each operation, and mm is the number of cells with nonzero values.

Each of the next mm lines contains three integers rr, cc, and aa, representing that the cell at row rr and column cc has the initial value aa. It is guaranteed that the rest of the matrix cells are 00.

It is guaranteed that 1r,cn1 \le r, c \le n.

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