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
This is probably a matrix. Calculates the maximum sum of a child matrix... But a little more. That is, the matrix is circular .. For example, columns n and 1st are connected.
Idea: Increase the matrix by 4 times. The ring problem is solved when the matrix is 4 times bigger. Then, we only need to enumerate matrices smaller than n * n during enumeration .. The specific method is similar to this question.
Code:
#include <stdio.h>#include <string.h>#include <limits.h>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;}