Title Source:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=3&page= Show_problem&problem=44
Background
A problem that's simple-to-solve in one dimension was often much more difficult-solve in more than one dimension. Consider satisfying a Boolean expression in conjunctive normal form in which each conjunct consists of exactly 3 disjuncts . This problem (3-SAT) is np-complete. The problem 2-sat is solved quite efficiently, however. In contrast, some problems belong to the same complexity class regardless of the dimensionality of the problem.
The problem
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 or greater located within the whole array. As an example, the maximal sub-rectangle of the array:
is in the Lower-left-hand corner:
and has the sum of 15.
Input and Output
The input consists of an array of integers. The input begins with a single positive an integer N on a line by itself indicating the size of the square and the Dimen Sional Array. This was followed by integers separated by white-space (newlines and spaces). These integers make to the array in row-major order (i.e., all numbers on the first row, left-to-right, then all numbers o n the second row, left-to-right, etc.). N may be as large as 100. The numbers in the array would be in the range [-127, 127].
The output is the sum of the maximal sub-rectangle.
Sample Input
40-2-7 0 9 2-6 2-4 1-4 1-18 0-2
Sample Output
15
Problem Solving Ideas:
Test instructions: The n*n matrix is given, and the maximum value of the matrix is obtained.
The application of the maximal continuous subsequence sequence is one-dimensional, the matrix is two-dimensional, so we can convert the matrix to one-dimensional to calculate.
That is, the enumeration matrix of successive lines of the merge, so that the conversion to one-dimensional, and then the maximum sub-sequence of the algorithm to seek, update the maximum value can be.
Code:
1#include <bits/stdc++.h>2 3 using namespacestd;4 5 inttable[ -][ -];6 intsum[ -];7 intN;8 9 intmax_continuous_sum ()Ten { One intmaxs=0, s=0; A for(intI=0; i<n; i++) - { - if(s>=0) s+=Sum[i]; the Elses=Sum[i]; -Maxs = Maxs>s?maxs:s; - } - returnMaxs; + } - intMain () + { ACIN >>N; at intmaxsum=0; - inttmp; - for(intI=0; i<n; i++) - { - for(intj=0; j<n; J + +) - { inCIN >>Table[i][j]; -sum[j]=Table[i][j]; to } +TMP =max_continuous_sum (); -Maxsum = maxsum>tmp?maxsum:tmp; the for(intj=i-1; j>=0; j--) * { $ for(intk=0; k<n; k++)Panax Notoginsengsum[k]+=Table[j][k]; -TMP =max_continuous_sum (); theMaxsum = maxsum>tmp?maxsum:tmp; + } A } thecout << maxsum <<Endl; + return 0; -}
UVa 108-maximum Sum (maximum consecutive subsequence)