最大子矩阵
Time Limit: 30000/10000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2915 Accepted Submission(s): 1462
Problem Description
给你一个m×n的整数矩阵,在上面找一个x×y的子矩阵,使子矩阵中所有元素的和最大。
Input
输
入数据的第一行为一个正整数T,表示有T组测试数据。每一组测试数据的第一行为四个正整数m,n,x,y(0<m,n<1000 AND
0<x<=m AND
0<y<=n),表示给定的矩形有m行n列。接下来这个矩阵,有m行,每行有n个不大于1000的正整数。
Output
对于每组数据,输出一个整数,表示子矩阵的最大和。
Sample Input
1
4 5 2 2
3 361 649 676 588
992 762 156 993 169
662 34 638 89 543
525 165 254 809 280
Sample Output
2474
Author
lwg
Source
代码:
1 #include<cstring> 2 #include<cstdio> 3 #include<cstdlib> 4 using namespace std; 5 const int maxn=1005; 6 int n,m,x,y; 7 __int64 map[maxn][maxn]; 8 int main(){ 9 int cas; 10 //system("cd desktop\codeblock\problem"); 11 //system("call test.in"); 12 //system("pause"); 13 //freopen("test.in","r",stdin); 14 scanf("%d",&cas); 15 while(cas--){ 16 scanf("%d%d%d%d",&n,&m,&x,&y); 17 memset(map,0,sizeof(map)); 18 for(int i=1;i<=n;i++){ 19 for(int j=1;j<=m;j++){ 20 scanf("%I64d",&map[i][j]); 21 map[i][j]+=(map[i-1][j]+map[i][j-1]-map[i-1][j-1]); 22 } 23 } 24 __int64 ans=0; 25 __int64 val ; 26 for(int i=x;i<=n;i++){ 27 for(int j=y;j<=m;j++){ 28 val=map[i][j]-map[i-x][j]-map[i][j-y]+map[i-x][j-y]; 29 if(ans<val)ans=val; 30 } 31 } 32 printf("%I64d ",ans); 33 } 34 return 0; 35 }