其中,A的子矩阵指在A中行和列均连续的一块。
接下来n行,每行m个整数,表示矩阵A。
-1 -4 3
3 4 -1
-5 -2 8
对于100%的数据,1<=n, m<=500,A中每个元素的绝对值不超过5000。
Thinking:
#include<iostream>
#define MIN -5001
using namespace std;
int main()
{
bool hasUpdate=false;
int i,j,k,row,col,temp,maxElem=MIN,tempSum,maxSum=0;
cin>>row>>col;
int **record=new int*[row+1];
for(i=0;i<=row;i++)
record[i]=new int[col+1]();
for(i=1;i<=row;i++)
{
for(j=1;j<=col;j++)
{
cin>>temp;
if(temp>maxElem)//find the minimum number of the whole array.
maxElem=temp;
record[i][j]=record[i-1][j]+temp;
}
}
for(i=1;i<=row;i++)
{
for(j=i;j<=row;j++)
{
tempSum=0;
for(k=1;k<=col;k++)//the maximum-sum sub-array algorithm
{
temp=record[j][k]-record[i-1][k];
if(tempSum>0)
tempSum+=temp;
else
tempSum=temp;
if(tempSum>maxSum)
{
maxSum=tempSum;
hasUpdate=true;
}
}
}
}
if(hasUpdate)
cout<<maxSum<<endl;
else//if maxSum never update, the maxSum is maxElem.
cout<<maxElem<<endl;
return 0;
}
631




被折叠的 条评论
为什么被折叠?



