Directory
1 Problem Description
2 Solutions
1 problem description Problem Descriptiongiven a n*m matrix A, find a non-empty matrix in a, making the element and maximum in this sub-matrix.
wherein, A's sub-matrix refers to a row and column in a continuous block. Input Formatthe first line of input contains two integers n, m, respectively, representing the number of rows and columns of matrix A.
the next n rows, m integers per line, represent matrix A. output FormatThe output line contains an integer that represents the element and the largest sub-matrix in a. Sample Input3 3
-1-4 3
3 4-1
-5-2 8Sample OutputTenSample Descriptiontake the last column, and the 10. data size and conventionsfor 50% of data, 1<=n, m<=50;
for 100% of data, 1<=n, the absolute value of each element in M<=500,a does not exceed 5000.
2 Solutions
Code reference from the end of the article, the same idea of Java version run timeout. Please refer to the final reference for specific ideas.
The specific code is as follows:
ImportJava.util.Scanner; Public classMain { Public Static intN, M; Public Static Long[] map; Public Static Longresult =Long.min_value; Public Static voidMain (string[] args) {Scanner in=NewScanner (system.in); N=In.nextint (); M=In.nextint (); Map=New Long[N][m]; for(inti = 0;i < n;i++) for(intj = 0;j < m;j++) Map[i][j]=In.nextlong (); for(intStart = 0;start < n;start++) {//Start line Long[] ring =New Long[M]; Long[] DP =New Long[M]; for(intEnd = Start;end < n;end++) {//End Line for(intj = 0;j < m;j++)//computes each column element of the Start~end row andRING[J] + =Map[end][j]; Result= Math.max (Result, ring[0]); dp[0] = ring[0]; for(intj = 1;j < m;j++) { if(Dp[j-1] < 0) Dp[j]=Ring[j]; ElseDp[j]= Dp[j-1] +Ring[j]; Result=Math.max (result, dp[j]); }}} System.out.println (Result); }}
Resources:
1. Blue Bridge Cup The largest sub-array of previous questions
Algorithm Note _176: Previous questions Max Sub-array (Java)