10827 - Maximum sum on a torus
Time limit: 3.000 seconds
A grid that wraps both horizontally and vertically is called a torus. Given a torus where each cell contains an integer, determine the sub-rectangle with the largest sum. The sum of a sub-rectangle is the sum of all the elements in that rectangle. The grid below shows a torus where the maximum sub-rectangle has been shaded.
1 | -1 | 0 | 0 | -4 |
2 | 3 | -2 | -3 | 2 |
4 | 1 | -1 | 5 | 0 |
3 | -2 | 1 | -3 | 2 |
-3 | 2 | 4 | 1 | -4 |
Input
The first line in the input contains the number of test cases (at most 18). Each case starts with an integer N (1≤N≤75) specifying the size of the torus (always square). Then follows N lines describing the torus, each line containing N integers between -100 and 100, inclusive.
Output
For each test case, output a line containing a single integer: the maximum sum of a sub-rectangle within the torus.
Sample Input Output for Sample Input
2 5 1 -1 0 0 -4 2 3 -2 -3 2 4 1 -1 5 0 3 -2 1 -3 2 -3 2 4 1 -4 3 1 2 3 4 5 6 7 8 9 | 15 45 |
UVa 108 的加强版。
对于矩阵环,首先要预处理一下:把矩阵变成2N*2N。
并且要注意不要让子矩阵超过N*N。
完整代码:
/*0.079s*/
#include<cstdio>
#include<algorithm>
using namespace std;
int arr[155][155];
int main(void)
{
int t, n, nn, maxn, sum;
scanf("%d", &t);
while (t--)
{
scanf("%d", &n);
nn = n << 1;
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= n; ++j)
{
scanf("%d", &arr[i][j]);
arr[n + i][j] = arr[i][j]; ///列复制
arr[i][j] += arr[i - 1][j]; ///列叠加
arr[i][n + j] = arr[i][j]; ///行复制
}
for (int i = n + 1; i <= nn; ++i)
for (int j = 1; j <= n; ++j)
{
arr[i][j] += arr[i - 1][j]; ///接上,继续列叠加
arr[i][n + j] = arr[i][j]; ///行复制
}
maxn = 0;
for (int i = 1; i <= n; i++)
for (int j = i; j < n + i; j++)
{
sum = 0;
for (int beg = 1, k = 1; beg <= n && k < nn; k++)
{
if (k - beg >= n)///子矩阵不要爆表,爆了的话就从beg标记处开始
{
k = ++beg;
sum = 0;
}
sum += arr[j][k] - arr[i - 1][k];
sum = max(0, sum);
if (sum == 0) beg = k + 1;
maxn = max(maxn, sum);
}
}
printf("%d\n", maxn);
}
return 0;
}