UVA10827 Maximum sum on a torus【最大子段和+DP】

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.
在这里插入图片描述
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
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
Sample Output
15
45

问题链接UVA10827 Maximum sum on a torus
问题简述:寻找子矩阵和最大值,上下左右均可以联通了。
问题分析:将矩阵扩大4倍,这样就不用考虑上下左右联通问题,在一个矩阵内求和最大子矩阵即可。
程序说明:(略)
参考链接:(略)
题记:(略)

AC的C++语言程序如下:

/* UVA10827 Maximum sum on a torus */

#include <bits/stdc++.h>

using namespace std;

const int N = 75;
int a[N * 4][N * 4], sum[N * 4];

int main()
{
    int t, n;
    scanf("%d", &t);
    while(t--) {
        scanf("%d", &n);
        for(int i = 0; i < n; i++)
            for(int j = 0; j < n; j++) {
                scanf("%d", &a[i][j]);
                a[i + n][j] = a[i][j + n] = a[i + n][j + n] = a[i][j];
            }

        int ans = -0x7F7F7F7F;
        for(int x = 0; x < n; x++)
            for(int y = 0; y < n; y++) {
                memset(sum, 0, sizeof(sum));
                for(int i = x; i < x + n; i++) {
                    int sum2 = 0;
                    for(int j = y; j < n + y; j++) {
                        sum[j] += a[i][j];
                        sum2 += sum[j];
                        ans = max(ans, sum2);
                    }
                }
            }

        printf("%d\n", ans);
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值