给定一个由整数组成二维矩阵(r*c),现在需要找出它的一个子矩阵,使得这个子矩阵内的所有元素之和最大,并把这个子矩阵称为最大子矩阵。
例子:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
其最大子矩阵为:
9 2
-4 1
-1 8
其元素总和为15。
Input
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
每组测试数据:
第一行有两个的整数r,c(0<r,c<=100),r、c分别代表矩阵的行和列;
随后有r行,每行有c个整数;
Output
输出矩阵的最大子矩阵的元素之和。
1
4 4
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
Sample Output
15
#include <iostream>
#include <cstring>
using namespace std;
const int maxn=105;
const int inf=1e9;
int a[maxn][maxn];
int b[maxn];
int r,c;
int MaxSum(){
int ret=-inf,tmp=0;
for(int i=0;i<c;i++){
if(tmp<0){
tmp=b[i];
}else{
tmp+=b[i];
}
if(tmp>ret){
ret=tmp;
}
}
return ret;
}
int main(){
int t,i,j,k;
cin>>t;
while(t--){
cin>>r>>c;
for(i=0;i<r;i++){
for(j=0;j<c;j++){
cin>>a[i][j];
}
}
int ans=-inf;
for(i=0;i<r;i++){
memset(b,0,sizeof(b));
for(j=i;j<r;j++){
for(k=0;k<c;k++){
b[k]+=a[j][k];
}
int tmp=MaxSum();
if(tmp>ans)
ans=tmp;
}
}
cout<<ans<<endl;
}
return 0;
}