这一题是求最大子矩阵,以后肯定还会经常碰到这样一类的题目
上原题;
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.
As an example, the maximal sub-rectangle of the array:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
is in the lower left corner:
9 2
-4 1
-1 8
and has a sum of 15.
As an example, the maximal sub-rectangle of the array:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
is in the lower left corner:
9 2
-4 1
-1 8
and has a sum of 15.
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].
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
思路:
刚开始
想到会不会用之前的求最大矩形的方法,以每一行进行遍历,后来想半天没想出来,后来看别人的代码才知道其实也就是暴力遍历,把高度为1,2,3,,,N的情况遍历一遍,找出最大的情况,只不过在遍历每一种高的情况时,会用到最大连续子序列,具体的做法是: 在输入的时候就注意一下,用a[i][j]表示第j列的前i行元素的和,将每一列看成是一个小矩形,这样要找出以i为上顶,的高度为high的最大矩阵,先得到s1,s2,s3,,,Sn,其中,Sk=a[i+high-1][k]-a[i-1][k],找出这段数列的最大连续子序列即可,关键是求最大连续子序列的时候要找一个好一点的算法,因为之前已经有两个for循环了,如果算法时间复杂度不行的话,会超时的(这一题要求还好,n最大就100),大家可以看这个网站最大连续子序列,我用的就是算法四,非常巧妙的一个算法,虽然无法确定最大连续子序列的位置,但是时间复杂度只有O(n),下面上代码:
<span style="font-family:KaiTi_GB2312;font-size:24px;">//Li Wenjun
//emai:1542113545@qq.com
/*
「“04.24,サクラと东京スカイツリーに行った。そこは世界で一番暖かいところだ。”
“04.26,サクラと明治神宫に行った。そこで结婚式お挙げる人がいた。”
“04.25,サクラとデイズニーに行った。お化け屋敷が怖かったけど、サクラがいたから、全然怖くわなかった。”
“サクラのことが大好き。”」
*/
#include<stdio.h>
#include<string.h>
#include<math.h>
#include <iostream>
#include <algorithm>
using namespace std;
int a[101][101];
int maxs=0,n;
bool dp(int numbs,int row)
{
int thisnum=0,thismax=0;
for(int j=1;j<=n;j++)
{
thisnum+=(a[row+numbs-1][j]-a[row-1][j]);
if(thisnum>thismax)
thismax=thisnum;
else if(thisnum<0)
thisnum=0;
}
if(thismax>maxs)
maxs=thismax;
return true;
}
int main()
{
cin.tie(0);
cin.sync_with_stdio(false);
// freopen("in.txt","r",stdin);
while(cin>>n)
{
int temp;
maxs=0;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
cin>>temp;
a[i][j]=a[i-1][j]+temp;
}
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n-i+1;j++)
{
dp(i,j);
}
}
cout<<maxs<<endl;
}
return 0;
}
</span>
还要继续加油!!
111