最大子矩阵和

来源:互联网 发布:mac键盘部分按键失灵 编辑:程序博客网 时间:2024/05/29 13:11

Problem H

Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 24   Accepted Submission(s) : 11
Problem Description
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1 x 1 or greater located within the whole array. The sum of a rectangle is the sum of all the elements in that rectangle. In this problem the sub-rectangle with the largest sum is referred to as the maximal sub-rectangle.<br><br>As an example, the maximal sub-rectangle of the array:<br><br>0 -2 -7 0<br>9 2 -6 2<br>-4 1 -4 1<br>-1 8 0 -2<br><br>is in the lower left corner:<br><br>9 2<br>-4 1<br>-1 8<br><br>and has a sum of 15.<br>
 

Input
The input consists of an N x N array of integers. The input begins with a single positive integer N on a line by itself, indicating the size of the square two-dimensional array. This is followed by N 2 integers separated by whitespace (spaces and newlines). These are the N 2 integers of the array, presented in row-major order. That is, all numbers in the first row, left to right, then all numbers in the second row, left to right, etc. N may be as large as 100. The numbers in the array will be in the range [-127,127].<br>
 

Output
Output the sum of the maximal sub-rectangle.<br>
 

Sample Input
40 -2 -7 0 9 2 -6 2-4 1 -4 1 -18 0 -2
 

Sample Output

15

之前一个课件上的解释就很权威,做法是枚举,根据子矩阵的特性来解决

每次枚举矩阵最上的行high和最下的行low,

再把这个子矩阵每一行的值相加,压缩成一维数组,

对于这个数组求最大字段和

这样就求出了以high行和low行为界限的最大子矩阵了

 

#include<iostream>
#include<stdio.h>
#include<string.h>using namespace std;int a[101][101],b[101],n;int solve (int b[],int n){    int i,max=0,c=0;    for(i=1;i<=n;i++)    {        if(c>0)        c+=b[i];        else c=b[i];        if(max<c)        max=c;        }     return max;    }int main(){    int i,j,k,l,n;    int maxx,max;    while(cin>>n)    {        memset(a,0,sizeof(a));        for(i=1;i<=n;i++)        for(j=1;j<=n;j++)        cin>>a[i][j];        max=0;        for(i=1;i<=n;i++)        {            for(j=1;j<=n;j++)            b[j]=0;            for(j=i;j<=n;j++)            {                for(k=1;k<=n;k++)                {                    b[k]+=a[j][k];                    }                int maxx=solve(b,n);                if(maxx>max)                max=maxx;                }            }        cout<<max<<endl;    }    return 0;    }