1084: [SCOI2005]最大子矩阵
Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 1705 Solved: 864
[ Submit][ Status][ Discuss]
Description
这里有一个n*m的矩阵,请你选出其中k个子矩阵,使得这个k个子矩阵分值之和最大。注意:选出的k个子矩阵不能相互重叠。
Input
第一行为n,m,k(1≤n≤100,1≤m≤2,1≤k≤10),接下来n行描述矩阵每行中的每个元素的分值(每个元素的分值的绝对值不超过32767)。
Output
只有一行为k个子矩阵分值之和最大为多少。
Sample Input
3 2 2
1 -3
2 3
-2 3
1 -3
2 3
-2 3
Sample Output
9
感觉dp非常弱。。省赛前得抓紧练了。。。
一维的时候很简单。。。
二维的时候设f[i][j][k]为第一列到i行第二列到j行取了k个的最大价值
dp方程如下:
f[i][j][k] = max(f[i-1][j][k],f[i][j-1][k]) (苟蒻老是忘这个)
f[i][j][k] = max(f[i][l][k-1] + s2[j] - s2[l])
f[i][j][k] = max(f[l][j][k-1] + s1[i] - s1[l])
如果 i == j
f[i][j][k] = max(f[l][l][k-1] + s1[i] - s1[l] + s2[j] - s2[l])
#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;
}