Description
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1*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.Input
The input consists of an N * 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].Output
Output the sum of the maximal sub-rectangle.Sample Input
4 0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2
Sample Output
15
題解:怎麼說呢。。就是第一行的一個序列加到第二行,找到他們的和序列的最大子序列,然後他們的和序列再加第三行,再找,每加一次找一次,加到第n行。
然後從第二行開始,按照上面的進行,再從第三行開始..... 直到第n行....
每次都要更新他們的子矩陣的的最大值,用一個變量更新
不說了,上代碼,最下面有輸出截圖
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n,sum,f,Max;
int b[20000];
int dp[150][150];
int main()
{
f=-100;
cin>>n;
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
{
cin>>dp[i][j];
}
for(int k=0; k<n; k++)
{
memset(b,0,sizeof(b)); // 一定每次記得清零
for(int i=k; i<n; i++)
{
for(int j=0; j<n; j++)
{
b[j]+=dp[i][j];
}
sum = Max =-100; //賦很小的值
for(int i=0; i<n; i++)
{
if (sum<0)
sum = b[i];
else
sum += b[i];
if (Max < sum)
Max = sum;
}
if(f<Max) // 每次都要比較更新最大子矩陣和
f=Max;
}
}
cout<<f<<endl;
}
