To solve this problem, we need to determine the minimum number of operations required to make all elements in a matrix non-negative. Each operation allows us to add 1 to all elements in a row or column.
Approach
The key insight to solve this problem efficiently is to recognize that the minimum number of operations can be derived from the maximum values in each row and column of the matrix (after adjusting for non-negative values). Here's the detailed approach:
- Adjust Matrix Values: For each element in the matrix, compute the value
d[i][j] = max(0, -a[i][j])wherea[i][j]is the original element. This gives us the number of increments needed for each element to become non-negative if no row or column operations are applied. - Sum of Row Maxima: Calculate the sum of the maximum values in each row of the adjusted matrix
d. This sum represents the number of operations needed if we only use row increments. - Sum of Column Maxima: Calculate the sum of the maximum values in each column of the adjusted matrix
d. This sum represents the number of operations needed if we only use column increments. - Minimum Operations: The answer is the minimum of the sum of row maxima and the sum of column maxima, as this gives the optimal number of operations.
Solution Code
n, m = map(int, input().split())
matrix = []
for _ in range(n):
row = list(map(int, input().split()))
matrix.append(row)
# Compute d matrix and row maxima sum
sum_row = 0
d_matrix = []
for row in matrix:
d_row = [max(0, -x) for x in row]
d_matrix.append(d_row)
sum_row += max(d_row)
# Compute column maxima sum
sum_col = 0
for j in range(m):
col_max = 0
for i in range(n):
if d_matrix[i][j] > col_max:
col_max = d_matrix[i][j]
sum_col += col_max
print(min(sum_row, sum_col))
Explanation
- Adjust Matrix: The
d_matrixis created where each element is the number of increments needed for the original element to become non-negative. - Row Maxima: For each row, the maximum value in
d_matrixgives the number of row increments needed for that row to make all elements non-negative. Summing these maxima gives the total row operations. - Column Maxima: Similarly, the maximum value in each column of
d_matrixgives the number of column increments needed for that column, and summing these gives the total column operations. - Optimal Result: The minimum of the two sums (row and column operations) gives the minimal number of operations needed to make all elements non-negative. This is because using either row or column operations (whichever is fewer) will always be optimal.
This approach efficiently computes the solution with a time complexity of O(n*m), which is optimal for the given problem constraints. It ensures that we find the minimal operations by leveraging the maximum values in rows and columns of the adjusted matrix.


作者声明:本文包含人工智能生成内容。