Problem H
Maximum sum on a torus
Input: Standard Input
Output: Standard Output
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 |
Problem setter: Jimmy Mårdell
Special Thanks: Derek Kisman, Md. Kamruzzaman
题意:给出一个n*n的矩阵,你要找出一个 “和最大”的子矩形。注意矩形能够跨越边界到另一边。
思路:我们把一个矩形扩充成4个并在一起,那么就解决了会“跨越”的问题了。于是怎么做呢?追求高效的你可能正在苦思冥想有没有什么快速一点的算法。。。。头脑简单的我只能暴力解决了,枚举矩形的左上角,枚举长和宽,然后求最大就行了 ,复杂度是O(n^4),不过也是能过的。。。。然后求最大的时候不要用max函数,好像挺慢的,自己用if判断会快一点。。。。
代码:
#include<iostream>
#include<cstdio>
#include<stdio.h>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
const int maxn = 150+5;
int sum[maxn][maxn];
int n;
//inline int max(int &a, int &b) { return a > b ? a : b; } 这个很慢。。。
void input()
{
scanf("%d", &n);
memset(sum, 0, sizeof(sum));
for (int i = 1; i <= n;++i)
for (int j = 1; j <= n; ++j)
{
scanf("%d", &sum[i][j]);
sum[i + n][j] = sum[i][j];
sum[i][j + n] = sum[i][j];
sum[i + n][j + n] = sum[i][j];
}
for (int i = 1; i <= 2 * n;++i)
for (int j = 1; j <= 2 * n; ++j)
sum[i][j] += sum[i - 1][j] + sum[i][j - 1] - sum[i - 1][j - 1];
}
void solve()
{
int ans = -1e9,val;
for (int i = 1; i <= n;++i)
for (int j = 1; j <= n; ++j)
{
for (int l = 1; l <= n;++l)
for (int w = 1; w <= n; ++w)
{
val = sum[i + w - 1][j + l - 1] - sum[i + w - 1][j - 1] - sum[i - 1][j + l - 1] + sum[i - 1][j - 1];
if (ans < val) ans = val;
}
}
printf("%d\n", ans);
}
int main()
{
int T; cin >> T;
while (T--)
{
input();
solve();
}
}