The computer broke down and forgot to send it.
Title: Returns the number of the largest sub-arrays in a two-dimensional integer array.
Requirements: Enter a two-dimensional shape array with positive and negative numbers in the array.
A two-dimensional array is connected to the end of the line, like a belt.
One or more consecutive integers in an array make up a sub-array, each of which has a and.
The maximum value for the and of all sub-arrays.
Ideas:
The maximum subarray of two-dimensional array and the one-dimensional array are combined to find the maximum subarray.
Code:
#include <iostream>#include<cstring>#include<assert.h>Const intN = -;Const intINF =-9999;using namespacestd;voidOutputintA[][n],intNintHeadintFootintBeginintLast )//head, foot represents the upper and lower bounds, begin, last represents the left and right bounds {inti,j; cout<<"the sub-arrays are:"<<Endl; for(I=head; i<=foot; i++) { if(Last <begin) { for(J=begin; j<n; J + +) {cout<<a[i][j]<<" "; } for(j=0; j<=last; J + +) {cout<<a[i][j]<<" "; } cout<<Endl; } Else { for(J=begin; j<=last; J + +) {cout<<a[i][j]<<" "; } cout<<Endl; }} cout<<Endl;}intMaxsubarray (intA[],intNint&begin,int&Last ) {Assert (a!=null && n>0); intMax =INF; intsum; inti,j,k; for(i=0; i<n; i++) {sum=0; for(j=i; j<n; J + +) {sum+=A[j]; if(Sum >max) {Max=sum; Begin=i; Last=J; } } for(k=0; k<i; k++)//starting from the first {sum+=A[k]; if(Sum >max) {Max=sum; Begin=i; Last=K; } } } returnMax;}intFindmaxsubmatrix (intA[][n],intN) {intTmpsum[n]; intMax =INF; intbegin, last, Begin1, Last1, head, foot; //enumerate possible combinations of all rows for(intI=0; i<n; i++) { //the tmpsum will be cleared 0memset (Tmpsum,0,sizeof(tmpsum)); for(intJ=i; j<n; J + +) { //plus the elements of the current row for(intk=0; k<n; k++)//each column{Tmpsum[k]+=A[j][k]; } intTmpmax =Maxsubarray (Tmpsum, N, Begin1, last1); if(Tmpmax >max) {Begin=begin1; Last=Last1; Head=i; Foot=J; Max=Tmpmax; }}} output (A, n, head, foot, begin, last); returnMax;}intMain () {intA[n][n]; intN//the size of the arraycout<<"Please enter the size of n in the array n*n:"<<Endl; while(Cin>>n &&N) { for(intI=0; i<n; i++) { for(intj=0; j<n; J + +) { intk=rand (); A[I][J]= k%2==0? rand ()% -+1:(-rand ()% -+1); } } for(intI=0; i<n; i++) { for(intj=0; j<n; J + +) {cout<<a[i][j]<<" "; } cout<<Endl; } cout<<Endl; cout<<"the number of the largest sub-arrays is:"<<findmaxsubmatrix (A, N) <<Endl; } return 0;}
Test:
1.n=4
2.n=5
Sentiment:
The program is still a little cumbersome, you have to define a K to start from the beginning.
Two-dimensional array-end-to-end concatenated maximum sub-array