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.
主要思想就是降维,源代码如下:
 1 #include <stdio.h>

 2 #include <stdlib.h>

 3 #define M 101

 4 int num[M][M];

 5 int N;

 6 

 7 int submax(int a[M])

 8 {

 9 int i,pre=a[1],max=0;

10 for(i=2;i<=N;i++)

11 {

12 if(a[i]+pre>a[i])

13 pre=a[i]+pre;

14 else

15 pre=a[i];

16 if(pre>max)

17 max=pre;

18 }

19 return max;

20 }

21 

22 int submax2()

23 {

24 int b[M];

25 int i,j,k,max=0;

26 for(i=1;i<=N;i++)

27 {

28 memset(b,0,sizeof(b));

29 for(j=i;j<=N;j++)

30 {

31 for(k=1;k<=N;k++)

32 b[k]+=num[j][k];

33 int ff=submax(b);

34 if(ff>max) max=ff;

35 }

36 }

37 return max;

38 }

39 

40 int main()

41 {

42 int i,j,k;

43 scanf("%d",&N);

44 for(i=1;i<=N;i++)

45 for(j=1;j<=N;j++)

46 scanf("%d",&num[i][j]);

47 printf("%d\n",submax2());

48 

49 return 0;

50 }

 

你可能感兴趣的:(poj)