UVa 10827 Maximum sum on a torus (贪心&矩阵环中的最大子矩阵和)

本文介绍了一种解决矩形环中寻找最大和子矩形的问题,通过将矩形环扩展为2N*2N的矩阵并进行特殊处理来避免超出N*N的限制,最终实现了高效求解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

10827 - Maximum sum on a torus

Time limit: 3.000 seconds

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1768

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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值