(压缩) ----- 最大子矩阵
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
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
# include <iostream.h>
# include <stdio.h>
# include <string.h>
# define N 1000
int arr[N+1][N+1];
__int64 sum[N+1][N+1]; //记得改成64位,否则WA
__int64 temp[N+1][N+1];
int main()
{
int t, i, j, x, y, m, n;
__int64 max,mid;
scanf("%d", &t);
while (t--)
{
scanf("%d %d %d %d", &m, &n, &x, &y);
memset(sum, 0, sizeof(sum));
for (i=1; i<=m; ++i)
{
for (j=1; j<=n; ++j)
{
scanf("%d", &arr[i][j]);
sum[i][j] = sum[i-1][j] + arr[i][j];
}
}
for (i=x; i<=m; ++i)
{
for (j=1; j<=n; ++j)
{
temp[i][j] = sum[i][j] - sum[i-x][j];
}
}
for (i=x; i<=m; ++i)
{
for (j=y; j<=n; ++j)
{
mid = 0;
for (int k=0; k<y; ++k)
{
mid += temp[i][j-k];
}
if (mid > max)
max = mid;
}
}
printf("%I64d\n", max);
}
return 0;
}
# include <stdio.h>
# include <string.h>
# define N 1000
int arr[N+1][N+1];
__int64 sum[N+1][N+1]; //记得改成64位,否则WA
__int64 temp[N+1][N+1];
int main()
{
int t, i, j, x, y, m, n;
__int64 max,mid;
scanf("%d", &t);
while (t--)
{
scanf("%d %d %d %d", &m, &n, &x, &y);
memset(sum, 0, sizeof(sum));
for (i=1; i<=m; ++i)
{
for (j=1; j<=n; ++j)
{
scanf("%d", &arr[i][j]);
sum[i][j] = sum[i-1][j] + arr[i][j];
}
}
for (i=x; i<=m; ++i)
{
for (j=1; j<=n; ++j)
{
temp[i][j] = sum[i][j] - sum[i-x][j];
}
}
for (i=x; i<=m; ++i)
{
for (j=y; j<=n; ++j)
{
mid = 0;
for (int k=0; k<y; ++k)
{
mid += temp[i][j-k];
}
if (mid > max)
max = mid;
}
}
printf("%I64d\n", max);
}
return 0;
}