UVa 10827 - Maximum sum on a torus
题目大意:UVa 108 - Maximum Sum的加强版,求最大子矩阵和,不过矩阵是可以循环的,矩阵到结尾时可以循环到开头。开始听纠结的,想着难道要分情况讨论吗?!就去网上搜,看到可以通过补全进行处理,也是,通过补全一个相同的,问题就迎刃而解了,所以把n*n的矩阵扩展成2n*2n的矩阵就好了。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <cstdio> 2 #include <cstring> 3 #define MAXN 160 4 5 int a[MAXN][MAXN], sum[MAXN][MAXN]; 6 7 int main() 8 { 9 #ifdef LOCAL 10 freopen("in", "r", stdin); 11 #endif 12 int T; 13 scanf("%d", &T); 14 while (T--) 15 { 16 int n; 17 scanf("%d", &n); 18 memset(sum, 0, sizeof(sum)); 19 for (int i = 1; i <= n; i++) 20 { 21 for (int j = 1; j <= n; j++) 22 scanf("%d", &a[i][j]); 23 for (int j = n+1; j <= 2*n; j++) 24 a[i][j] = a[i][j-n]; 25 } 26 for (int i = n+1; i <= 2*n; i++) 27 for (int j = 1; j <= 2*n; j++) 28 a[i][j] = a[i-n][j]; 29 for (int i = 1; i <= 2*n; i++) 30 for (int j = 1; j <= 2*n; j++) 31 sum[i][j] = sum[i][j-1] + sum[i-1][j] - sum[i-1][j-1] + a[i][j]; 32 int max = a[1][1]; 33 for (int i = 1; i <= n; i++) 34 for (int p = 0; p < n; p++) 35 for (int j = 1; j <= n; j++) 36 for (int q = 0; q < n; q++) 37 { 38 int t = sum[i+p][j+q] - sum[i+p][j-1] - sum[i-1][j+q] + sum[i-1][j-1]; 39 if (t > max) max = t; 40 } 41 printf("%d\n", max); 42 } 43 return 0; 44 } 45 46