Description
Given a 2-dimensional array of positive and negative integers, find the sub-rectangle with the largest sum. The sum of a rectangle is the sum of the "the elements in" that rectangle. The problem the sub-rectangle with the largest sum are referred to as the
Maximal sub-rectangle. A Sub-rectangle is any contiguous sub-array of size 1x1 or greater located within the whole array. 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-hand corner and has the sum of 15.
Input
The input consists of an
NX
NArray of integers. The input begins with a single positive integer
NOn a line by itself indicating the size of the square and the dimensional array. This was followed by
N2 integers separated by white-space (newlines and spaces). These
N2integers make to the array in row-major order (i.e., all numbers to the first row, left-to-right, then all numbers on the Second row, left-to-right, etc.).
NMay is as large as 100. The numbers in the array would be in the range [−127, 127].
Output
The output is the sum of the maximal sub-rectangle. Test Instructions Analysis: The topic is relatively simple, given a n*n matrix, to find the matrix of the maximum and the neutron matrix. In the given example, the largest sub-matrix is
That is 15. Solution thinking: This is a two-dimensional array, to find the largest sub-matrix and, should think of using one-dimensional maximum sub-sequence and, then you can compress sub-matrices into sub-sequences, and then solve. 1) The matrix is shrunk to a column column, and the four columns are then evaluated for the maximum number of sub-sequences. 2) One-dimensional maximal sub-sequence and. The code is as follows:
#include <stdio.h>
#define MAX_N
int arr[max_n][max_n];
int Rowssum[max_n]; and
int N for each line;
int calc (int x, int y);
Int main ()
{
//freopen ("Input.txt", "R", stdin);
scanf ("%d", &n);
int i = 0;
Int j = 0;
int max =-1270000;
int sum = 0;
for (i=0;i<n;i++)
{
for (j=0;j<n;j++)
{
&NBS P &NBSP;SCANF ("%d", &arr[i][j]);
}
}
for (i=0;i<n;i++)
{
for (j=i ; j<n;j++)
{
sum = Calc (i,j); Calculation of column I to column J Maximum and
if (Sum>max)
& nbsp {
max = sum; {
&NBSP ; }
printf ("%d\n", Max);
return 0;
}
int calc (int x, int y)
{
int i = 0;
int j = 0;
int resultvalue =-1270000;
int thissum = 0;
for (i=0;i<n;i++)
{
Rowssum[i] = 0;
for (j=x;j<=y;j++)
{
Rowssum[i] = Rowssum[i] + arr[i][j];
}
}
Rowssum represents the and of each row for the specified column I to J.
Rowssum[] The maximum subsequence of this one-dimensional array and
for (i=0;i<n;i++)
{
Thissum = Thissum + rowssum[i];
if (Thissum>resultvalue)
{
Resultvalue = Thissum;
}
if (thissum<0)
{
thissum = 0;
}
}
return resultvalue;
}
URAL1146 & POJ1050 Maximum Sum (maximum contiguous subsequence and)