问题描述
小M负责管理一块农田,他需要通过修建两条灌溉渠道来提升作物的总产量。农田可以表示为一个nn行mm列的二维数组cropFieldcropField,其中cropField[i][j]cropField[i][j]代表第ii行第jj列的作物产量。小M的灌溉方案是:
- 一条渠道从上到下灌溉整行,另一条渠道从左到右灌溉整列。
- 被灌溉的行或列上的作物产量会加倍(即对应位置的作物产量变为原来的两倍)。
- 只能给每个作物位置加倍一次,即同一位置不能同时被两条渠道灌溉。
你需要帮小M找出哪一行和哪一列应该被灌溉,使得作物的总产量最大化。
测试样例
样例1:
输入:
m = 4, n = 4, cropField = [[2, 3, 1, 4], [1, 2, 0, 3], [4, 2, 1, 7], [3, 1, 4, 2]]
输出:64
样例2:
输入:
m = 3, n = 3, cropField = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
输出:78
样例3:
输入:
m = 2, n = 2, cropField = [[10, 20], [30, 40]]
输出:190
样例4:
输入:
m = 2, n = 3, cropField = [[10, 20], [30, 40], [50,60]]
输出:380
#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int solution(int m, int n, vector<vector<int>> &cropField) {
// Calculate initial total
int total = 0;
for (const auto& row : cropField) {
for (int val : row) {
total += val;
}
}
// Precompute row sums
vector<int> row_sum(n, 0);
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
row_sum[i] += cropField[i][j];
}
}
// Precompute column sums
vector<int> col_sum(m, 0);
for (int j = 0; j < m; ++j) {
for (int i = 0; i < n; ++i) {
col_sum[j] += cropField[i][j];
}
}
// Find the maximum total after choosing a row and a column
int max_total = total;
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
int current_total = total + row_sum[i] + col_sum[j] - cropField[i][j];
if (current_total > max_total) {
max_total = current_total;
}
}
}
return max_total;
}
int main() {
vector<vector<int>> cropField1 = {
{2, 3, 1, 4}, {1, 2, 0, 3}, {4, 2, 1, 7}, {3, 1, 4, 2}};
vector<vector<int>> cropField2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
vector<vector<int>> cropField3 = {{10, 20}, {30, 40}};
vector<vector<int>> cropField4 = {{10, 20}, {30, 40}, {50, 60}};
cout << (solution(4, 4, cropField1) == 64) << endl;
cout << (solution(3, 3, cropField2) == 78) << endl;
cout << (solution(2, 2, cropField3) == 190) << endl;
cout << (solution(2, 3, cropField4) == 380) << endl;
return 0;
}