设为首页 加入收藏

TOP

UVA 10827 Maximum sum on a torus(子矩阵之和变形)
2014-11-23 20:00:41 来源: 作者: 【 】 浏览:6
Tags:UVA 10827 Maximum sum torus 矩阵 之和 变形

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
251 -1 0 0 -42 3 -2 -3 24 1 -1 5 03 -2 1 -3 2-3 2 4 1 -431 2 34 5 67 8 9 1545

题意:大概就是给定一个矩阵。求一个子矩阵之和最大。。。但是多了一点。就是这个矩阵是环形的。。就是比如n列和第1列也算是相连的。


思路:把矩阵扩大4倍。变成一个4倍的矩阵,就解决了环的问题。然后枚举的时候只要枚举小于n*n的矩阵。。具体方法和这题类似


代码:


#include 
#include 
#include 

int t, n, num[160][160], sum[160], he, Max;

void init() {
    scanf("%d", &n);
    Max = -INT_MAX;
    for (int i = 0; i < n; i ++)
	for (int j = 0; j < n; j ++) {
	    scanf("%d", &num[i][j]);
	    num[i][j + n] = num[i + n][j] = num[i + n][j + n] = num[i][j];
	    if (Max < num[i][j])
		Max = num[i][j];
	}
}

int solve() {
    for (int i = 0; i < n; i ++) {
	for (int j = 0; j < n; j ++) {
	    memset(sum, 0, sizeof(sum));
	    for (int k = i; k < n + i; k ++) {
		he = 0;
		for (int l = j; l < n + j; l ++) {
		    sum[l] += num[k][l];
		    he += sum[l];
		    if (Max < he)
			Max = he;
		}
	    }
	}
    }
    return Max;
}
int main() {
    scanf("%d", &t);
    while (t --) {
	init();
	printf("%d\n", solve());
    }
    return 0;
}

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇[poj 1125]Stockbroker Grapevine.. 下一篇UVa 1452 - Jump(约瑟夫环变形)

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Python爬虫教程(从 (2025-12-26 16:49:14)
·【全269集】B站最详 (2025-12-26 16:49:11)
·Python爬虫详解:原 (2025-12-26 16:49:09)
·Spring Boot Java: (2025-12-26 16:20:19)
·Spring BootでHello (2025-12-26 16:20:15)