POJ1050总结

To the Max

题目来源

Description

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.

Input

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 100. The numbers in the array will be in the range [-127,127].

Output

Output the sum of the maximal sub-rectangle.

Sample Input

4
0 -2 -7 0 9 2 -6 2
-4 1 -4  1 -1

8  0 -2

Sample Output

15

我的代码

动规+前缀和。利用前缀和可以把矩阵压缩成一维的整数序列看待。如果这一块加上其前面一个数构成的最大块不能比自身大,那么此时最大块为自身,否则为相加的和。dp方程dp[k]=max(sum[j][k],sum[j][k]+dp[k-1]);

#include<stdio.h>
int dp[101][101];
int array[101][101];
int sum[101][101];//sum[i][j]记录第j列前i行的子段和 
int ans=-100000;
int max(int x,int y)
{
	return x>y?x:y;
}
int main()
{
	int n;
	scanf("%d",&n); 
	for (int i=0;i<n;i++)
	{
		for (int j=0;j<n;j++)
		{
			scanf("%d",&array[i][j]);
		}
	}
	for (int j=0;j<n;j++)
	{
		sum[0][j]=array[0][j];
	}
	for (int i=1;i<n;i++)
	{
		for (int j=0;j<n;j++)
		{
			sum[i][j]=sum[i-1][j]+array[i][j];
		}
	}
	for (int i=0;i<n;i++)
	{
		for (int j=i;j<n;j++)
		{
			int dp[101];
			if (i==0)
			{
				dp[0]=sum[j][0];
				if (dp[0]>ans)	ans=dp[0];
				for (int k=1;k<n;k++)
				{
					dp[k]=max(sum[j][k],sum[j][k]+dp[k-1]);
					if (dp[k]>ans)	ans=dp[k];
				}
			}
			else
			{
				dp[0]=sum[j][0]-sum[i-1][0];
				if (dp[0]>ans)	ans=dp[0];
				for (int k=1;k<n;k++)
				{
					dp[k]=max(sum[j][k]-sum[i-1][k],sum[j][k]-sum[i-1][k]+dp[k-1]);
					if (dp[k]>ans)	ans=dp[k];
				}
			}
		}
	}
	printf("%d",ans);
	return 0;
}

反思

简单题。以前在PTA上做过了。

发表评论