C_plus_plus_12345 @ 2024-11-29 21:02:56
#include <iostream>
#include <vector>
#include <numeric>
#include <limits>
using namespace std;
// 检查当前矩阵中是否有至少k个元素满足条件
int check_conditions(const vector<vector<int>>& matrix, int n, int m, int k)
{
int count = 0;
for (int i = 0; i < n; ++i)
{
int row_sum = accumulate(matrix[i].begin(), matrix[i].end(), 0);
for (int j = 0; j < m; ++j)
{
int col_sum = 0;
for (int r = 0; r < n; ++r)
{
col_sum += matrix[r][j];
}
if (matrix[i][j] >= row_sum + col_sum)
{
++count;
}
}
}
return count;
}
int min_minus_operations(vector<vector<int>>& matrix, int n, int m, int k)
{
int minus_operations = 0;
while (true)
{
// 检查当前矩阵是否满足条件
int current_count = check_conditions(matrix, n, m, k);
if (current_count >= k)
{
return minus_operations;
}
// 对矩阵进行minus操作
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
--matrix[i][j];
}
}
++minus_operations;
}
}
int main()
{
int n, m, k;
cin >> n >> m >> k;
vector<vector<int>> matrix(n, vector<int>(m));
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
cin >> matrix[i][j];
}
}
int result = min_minus_operations(matrix, n, m, k);
cout << result << endl;
return 0;
}
我把这玩意扔进 B3811 里边,后面仨测试点全
by wanshuhao @ 2024-11-29 21:08:09
check_conditions() 的问题,col_sum 被反复计算了
by wanshuhao @ 2024-11-29 21:08:57
@C_plus_plus_12345
by C_plus_plus_12345 @ 2024-11-29 21:12:04
@wanshuhao 请您具体描述一下问题。
by wanshuhao @ 2024-11-29 21:15:52
循环外预处理 col_sum
by wanshuhao @ 2024-11-29 21:18:40
int check_conditions(const vector<vector<int>>& matrix, int n, int m, int k)
{
int count = 0;
int row_sum[105] = {}, col_sum[105] = {};
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; ++j)
{
row_sum[i] += matrix[i][j];
col_sum[j] += matrix[i][j];
}
}
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < m; ++j)
{
if (matrix[i][j] >= row_sum[i] + col_sum[j])
{
++count;
}
}
}
return count;
}
by wanshuhao @ 2024-11-29 21:28:34
你的代码中有一个三重循环\ 注意到当 i 变化,j 和 r 固定时,col_sum不变\ 因此可以提前处理 col_sum 以避免重复的计算
by wanshuhao @ 2024-11-29 21:28:50
@C_plus_plus_12345