思路:
dp[i][j][k]:第一列选前i个第二列选前j个总共选了k个子矩阵的最大值
注意空矩阵也算子矩阵
代码:
#pragma GCC optimize(2) #pragma GCC optimize(3) #pragma GCC optimize(4) #include<bits/stdc++.h> using namespace std; #define fi first #define se second #define pi acos(-1.0) #define LL long long //#define mp make_pair #define pb push_back #define ls rt<<1, l, m #define rs rt<<1|1, m+1, r #define ULL unsigned LL #define pll pair<LL, LL> #define pli pair<LL, int> #define pii pair<int, int> #define piii pair<pii, int> #define pdd pair<long double, long double> #define mem(a, b) memset(a, b, sizeof(a)) #define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define fopen freopen("in.txt", "r", stdin);freopen("out.txt", "w", stout); //head const int N = 105; int dp[N][N][12], f[N][12]; int a[N][3], sum[N][3]; int main() { int n, m, k; scanf("%d %d %d", &n, &m, &k); for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) scanf("%d", &a[i][j]); for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) sum[i][j] = sum[i-1][j] + a[i][j]; } int ans = 0; if(m == 1) { for (int i = 1; i <= n; i++) { for (int j = 1; j <= k; j++) { f[i][j] = f[i-1][j]; for (int l = 0; l < i; l++) f[i][j] = max(f[i][j], f[l][j-1] + sum[i][1] - sum[l][1]); ans = max(ans, f[i][j]); } } } else { for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { for (int l = 1; l <= k; l++) { dp[i][j][l] = max(dp[i-1][j][l], dp[i][j-1][l]); for (int m = 0; m < i; m++) dp[i][j][l] = max(dp[i][j][l], dp[m][j][l-1] + sum[i][1] - sum[m][1]); for (int m = 0; m < j; m++) dp[i][j][l] = max(dp[i][j][l], dp[i][m][l-1] + sum[j][2] - sum[m][2]); if(i == j) for (int m = 0; m < i; m++) dp[i][j][l] = max(dp[i][j][l], dp[m][m][l-1] + sum[i][1] - sum[m][1] + sum[j][2] - sum[m][2]); ans = max(ans, dp[i][j][l]); } } } } printf("%d ", ans); return 0; }