Solution to poj 1050 “To the Max”
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.
To solve this problem, you need to know how to solve the largest sum of successive sub string. Then you could turn this problem from 2-dimension to 1 dimension.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | #include <stdio.h> #include <iostream> using namespace std; int getMax(int buf[100],int n) { int temp[101],max=n*(-127); memset(temp,0,sizeof(temp)); for(int i=1;i<=n;i++) { temp[i] = (temp[i-1]>0?temp[i-1]:0)+buf[i]; if(max<temp[i]) max=temp[i]; } return max; } int main(void) { int n,num[101][101],i,j,k,max,temp[101]; scanf("%d",&n); for(i=1;i<=n;i++) for(j=1;j<=n;j++) scanf("%d",&num[i][j]); max = -127*n*n; for(i=1;i<=n;i++) { memset(temp,0,sizeof(temp)); for(j=i;j<=n;j++) { for(k=1;k<=n;k++) { temp[k] += num[j][k]; } int this_max = getMax(temp,n); if(this_max>max) max = this_max; } } printf("%d\n",max); return 0; } |

没看明白啊!~~~~~~~~
额,你得先理解最大子串的DP算法,然后再进化一下就回啦~