To The Max

秒速五厘米 2022-07-31 20:27 239阅读 0赞

To The Max

Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 9296 Accepted Submission(s): 4507

Problem Description

Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1 x 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 x 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

  1. 4
  2. 0 -2 -7 0 9 2 -6 2
  3. -4 1 -4 1 -1
  4. 8 0 -2

Sample Output

  1. 15

Source

Greater New York 2001

这一题原来是先把每一行的列算成现线性的,到最后再进行行的

动态规划!现在不一样了,我用矩形思想再写一次发现AC了!

  1. #include<cstdio>
  2. #include<iostream>
  3. #include<algorithm>
  4. using namespace std;
  5. int a[105][105];
  6. int main()
  7. {
  8. int n,i,j,k,l,maxs,ans,f1,f2;
  9. while(cin>>n)
  10. {
  11. maxs=-10000;
  12. for(i=1;i<=n;i++)
  13. {
  14. for(j=1;j<=n;j++)
  15. {
  16. cin>>a[i][j];
  17. a[i][j]=a[i][j]+a[i-1][j]+a[i][j-1]-a[i-1][j-1];
  18. }
  19. }
  20. /* for(i=1;i<=n;i++)
  21. {
  22. for(j=1;j<=n;j++)
  23. {
  24. cout<<a[i][j]<<" ";
  25. }
  26. cout<<endl;
  27. }*/
  28. for(i=1;i<=n;i++)
  29. {
  30. for(j=1;j<=n;j++)
  31. {
  32. for(k=1;k<=i;k++)
  33. {
  34. for(l=1;l<=j;l++)
  35. {
  36. f1=i-k+1;f2=j-l+1;//这个是为了求出矩形的长和宽1
  37. ans=a[i][j]-a[i][j-f2]-a[i-f1][j]+a[i-f1][j-f2];
  38. maxs=max(ans,maxs);
  39. }
  40. }
  41. }
  42. }
  43. cout<<maxs<<endl;
  44. }
  45. }

发表评论

表情:
评论列表 (有 0 条评论,239人围观)

还没有评论,来说两句吧...

相关阅读