Description
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1*1 or greater located within the whole array. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the
sub-rectangle with the largest sum is referred to as the maximal sub-rectangle.
As an example, the maximal sub-rectangle of the array:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
is in the lower left corner:
9 2
-4 1
-1 8
and has a sum of 15.
As an example, the maximal sub-rectangle of the array:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
is in the lower left corner:
9 2
-4 1
-1 8
and has a sum of 15.
Input
The input consists of an N * N array of integers. The input begins with a single positive integer N on a line by itself, indicating the size of the square two-dimensional array. This is followed by N^2 integers separated by whitespace (spaces and newlines).
These are the N^2 integers of the array, presented in row-major order. That is, all numbers in the first row, left to right, then all numbers in the second row, left to right, etc. N may be as large as 100. The numbers in the array will be in the range [-127,127].
Output
Output the sum of the maximal sub-rectangle.
Sample Input
4 0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2
Sample Output
15
思路:
dp水题,四重循环
代码:
#include <iostream>
#include <stdio.h>
#include <map>
#include <vector>
using namespace std;
//sum[i][j] = sum[i][j-1] + sum[i-1][j] - sum[i-1][j-1]
typedef map<int, int> mii;
typedef vector<int> vi;
typedef pair<int, int> pii;
int a[110][110];//原始数据
int sum[110][110];//顶点到a[i][j]的矩阵和
int f[110][110];//以a[i][j]为右下角的所能形成的所有矩阵的最大值
int main()
{
int n;
int i, j, x, y;
int ans = 0;
scanf("%d", &n);
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
scanf("%d", &a[i][j]);
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
for(x = 1; x <= i; x++)
for(y = 1; y <= j; y++)
sum[i][j] += a[x][y];
for(i = 1; i <= n; i++)
for(j = 1; j <= n; j++)
{
for(x = 1; x <= i; x++)
for(y = 1; y <= j; y++)
{
int t = sum[i][j] + sum[x-1][y-1] - sum[i][y-1] - sum[x-1][j];
f[i][j] = max(t, f[i][j]);
}
ans = max(f[i][j],ans);
}
printf("%d", ans);
return 0;
}
/*
4
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
*/
本文介绍了一个关于二维数组中寻找最大子矩形和的问题,并提供了一种使用动态规划的方法来解决该问题。通过四重循环遍历所有可能的子矩阵,计算并更新每个子矩阵的和,最终找到具有最大和的子矩形。

2838

被折叠的 条评论
为什么被折叠?



