这里有一个n*m的矩阵,请你选出其中k个子矩阵,使得这个k个子矩阵分值之和最大。注意:选出的k个子矩阵不能相互重叠。
这里有一个n*m的矩阵,请你选出其中k个子矩阵,使得这个k个子矩阵分值之和最大。注意:选出的k个子矩阵不能相互重叠。
第一行为n,m,k(1≤n≤100,1≤m≤2,1≤k≤10),接下来n行描述矩阵每行中的每个元素的分值(每个元素的分值的绝对值不超过32767)。
只有一行为k个子矩阵分值之和最大为多少。
#include<cstdio> #include<iostream> #include<algorithm> #include<cstring> #include<string> #include<queue> #include<stack> #include<vector> #include<cstdlib> #include<map> #include<cmath> using namespace std; const int maxn = 110; int f1[maxn][15],f[maxn][maxn][15],n,m,K; int i,j,s1[maxn],s2[maxn],st[maxn]; int main() { #ifndef ONLINE_JUDGE #ifndef YZY freopen(".in","r",stdin); freopen(".out","w",stdout); #else freopen("yzy.txt","r",stdin); #endif #endif cin >> n >> m >> K; for (i = 1; i <= n; i++) for (j = 1; j <= n; j++) for (int k = 1; k <= K; k++) f[i][j][k] = -1E9; if (m == 1) { for (i = 1; i <= n; i++) scanf("%d",&s1[i]),s1[i] += s1[i-1]; for (int l = 1; l <= K; l++) for (i = l; i <= n; i++) { if (i > 1) f1[i][l] = f1[i-1][l]; for (j = 0; j < i; j++) f1[i][l] = max(f1[i][l],f1[j][l-1] + s1[i] - s1[j]); } cout << f1[n][K]; return 0; } else { for (i = 1; i <= n; i++) { scanf("%d%d",&s1[i],&s2[i]); s1[i] += s1[i-1]; s2[i] += s2[i-1]; } for (int l = 1; l <= K; l++) for (i = 0; i <= n; i++) for (j = 0; j <= n; j++) { if (i > 1) f[i][j][l] = max(f[i][j][l],f[i-1][j][l]); if (j > 1) f[i][j][l] = max(f[i][j][l],f[i][j-1][l]); int k; for (k = 0; k < i; k++) f[i][j][l] = max(f[i][j][l],f[k][j][l-1] + s1[i] - s1[k]); for (k = 0; k < j; k++) f[i][j][l] = max(f[i][j][l],f[i][k][l-1] + s2[j] - s2[k]); if (i == j) for (k = 0; k < i; k++) f[i][j][l] = max(f[i][j][l],f[k][k][l-1] + s1[i] + s2[i] - s1[k] - s2[k]); } cout << f[n][n][K]; } return 0; }