百练openjudge 1050:To the Max

1050:To the Max
查看 提交 统计 提示 提问
总时间限制: 5000ms 内存限制: 65536kB
描述
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1*1 or greater located within the whole array. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle.
As an example, the maximal sub-rectangle of the array:

0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
is in the lower left corner:

9 2
-4 1
-1 8
and has a sum of 15.
输入
The input consists of an N * N array of integers. The input begins with a single positive integer N on a line by itself, indicating the size of the square two-dimensional array. This is followed by N^2 integers separated by whitespace (spaces and newlines). These are the N^2 integers of the array, presented in row-major order. That is, all numbers in the first row, left to right, then all numbers in the second row, left to right, etc. N may be as large as 500. The numbers in the array will be in the range [-127,127].
输出
Output the sum of the maximal sub-rectangle.
样例输入
4

0 -2 -7 0 

9 2 -6 2

-4 1 -4 1 

-1 8 0 -2

样例输出

15


此题是一维最大连续串的拓展,那么怎么求一维的呢?就是给你一串连续的数怎么求出最大的子串和呢?这里有个现成的Kadane算法,证明比较繁琐,可以直接用,扫描一遍即可。

用sum记录当前和,实时跟新max ;当sum为负是再初始化为零。然后回到二维上面来,只要枚举一下化为一维即可!一维参考一下:http://blog.csdn.net/joylnwang/article/details/6859677,注意一下看结论,证明太过复杂。。。下面的代码以注释,看起来应该不难!


AC代码:


# include <stdio.h>
# include <string.h>
int s[510][510];
int g[510][510];
int main(){
	int n, i, j, k, l, m, Max, submax, sum;
	while(scanf("%d", &n)!=EOF){
		memset(s, 0, sizeof(s));
		Max=-200000000;
		for(i=1; i<=n; i++){
			for(j=1; j<=n; j++){
				scanf("%d", &g[i][j]);
				s[i][j]=s[i-1][j]+g[i][j];//s[i][j]表示第j列的前i个数字的和;
			}
		}
                //一一枚举起始行和终止行
		for(i=0; i<=n-1; i++){
			for(j=i+1; j<=n; j++){
				submax=-2000000000;
				sum=0;
                                //KadaneËã·¨
				for(k=1; k<=n; k++){
					sum=sum+s[j][k]-s[i][k];
					if(sum>submax){
						submax=sum;
					}
					if(sum<0){
						sum=0;
					}
				}
				if(submax>Max){
					Max=submax;
				}
			}
		}
		printf("%d\n", Max);
	}
	return 0;
} 



你可能感兴趣的:(动态规划,ACM,子串和,Kadane)