Uva--10827(贪心)
2014-07-27 14:31:33
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
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 |
思路:通过把矩阵扩展成四倍,然后就转化成二维的求最大连续和的问题了,(注意最长的长度不能超过n,所以要枚举起点把长度限制一下)。
1 /************************************************************************* 2 > File Name: p.cpp 3 > Author: Nature 4 > Mail: 564374850@qq.com 5 > Created Time: Sat 26 Jul 2014 01:46:52 PM CST 6 ************************************************************************/ 7 8 #include <cstdio> 9 #include <cstring> 10 #include <cstdlib> 11 #include <cmath> 12 #include <iostream> 13 #include <algorithm> 14 using namespace std; 15 const int INF = 0x3f3f3f3f; 16 17 int g[400][400],sumc[400][400]; 18 19 int main(){ 20 int Case,n,m; 21 scanf("%d",&Case); 22 while(Case--){ 23 scanf("%d",&n); 24 m = 2 * n; 25 for(int i = 1; i <= n; ++i){ 26 for(int j = 1; j <= n; ++j){ 27 scanf("%d",&g[i][j]); 28 g[i][j + n] = g[i][j]; 29 g[i + n][j] = g[i][j]; 30 g[i + n][j + n] = g[i][j]; 31 } 32 } 33 for(int i = 1; i <= m; ++i) 34 for(int j = 1; j <= m; ++j) 35 sumc[i][j] = sumc[i - 1][j] + g[i][j]; 36 int ans = -INF; 37 for(int i = 1; i <= m; ++i){ 38 for(int j = i; j <= m && j <= i + n - 1; ++j){ 39 for(int v = 1; v <= n; ++v){ 40 int tsum = 0,tmax = -INF; 41 for(int k = v; k <= v + n - 1; ++k){ 42 tsum += sumc[j][k] - sumc[i - 1][k]; 43 if(tsum < 0 && k < v + n - 1){ 44 tsum = sumc[j][k + 1] - sumc[i - 1][k + 1]; 45 ++k; 46 } 47 if(tsum > tmax) 48 tmax = tsum; 49 } 50 ans = tmax > ans ? tmax : ans; 51 } 52 } 53 } 54 printf("%d\n",ans); 55 } 56 return 0; 57 }