AcWing 126. The largest sum

Given a two-dimensional matrix containing integers, a sub-rectangle is any continuous sub-array with a size of 1 * 1 or greater located in the entire array.

The sum of the rectangle is the sum of all the elements in the rectangle.
In this problem, the sub-rectangle with the largest sum is called the largest sub-rectangle.

For example, the following array:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
Its largest sub-rectangle is:
9 2
-4 1
-1 8
It has the largest sum 15.

Input format The
input will contain an N*N integer array.
Enter only an integer N in the first line, which represents the size of the square two-dimensional array.
Starting from the second line, enter N2 integers separated by spaces and line breaks. They are the N2 elements in the two-dimensional array. The input sequence starts from the first line of the two-dimensional array and enters downwards line by line, the same line The data is entered one by one from left to right.
The numbers in the array will remain in the range of [-127,127].

The output format
outputs an integer, which represents the sum of the largest sub-rectangles.

Data range
1≤N≤100
Input example:
4
0 -2 -7 0 9 2 -6 2
-4 1 -4 1 -1
8 0 -2

Output example:
15

code show as below:

#include <iostream>
using namespace std;
const int N = 110;
int a[N][N];
int main()
{
    
    
    int n;
    cin>>n;
    for (int i = 1;i<=n;i++)
        for (int j = 1;j<=n;j++)
            {
    
    
                int x;
                cin>>x;
                a[i][j] = a[i-1][j]+x;
            }
   int  res = -1e8;
    for (int i = 1;i<=n;i++)
    {
    
    
        for (int j = i;j<=n;j++)
        {
    
    
            int f = 0;
            for (int k = 1;k<=n;k++)
            {
    
    
                int cnt =  a[j][k]-a[i-1][k];
                f = max(f,0)+cnt;
                res = max(res,f);
            }
        }
    }
    cout<<res<<endl;
    
}

Guess you like

Origin blog.csdn.net/m0_51955470/article/details/114085028