hdu1081最大子矩阵
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
求最大子矩阵。
方法一:
我们应类比一下一维最大子段和的那题,如果我们能将二维化为一维,那么在一维里求最大子段我们是有方法求的,所以我们将输入的数据先做如下处理:
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
处理后就是:
0 -2 -9 -9
9 11 5 7
-4 -3 -7 -6
-1 7 7 5
(这个样例只是按照每一行来用dp方法处理的,其实按照每一列来处理是一样可行的)。经过处理之后我们其实是很容易得到第k行第i列到第j列之间的子段和,注意:!k是可以从1到n的!得到之后那么我们就已经将二维化为了一维,对于特定的第i列到第j列之间的矩阵最大和,我们就转化为了第i列到第j列之间子段和在1到k行的
最大值(详见代码,细细体会)不过这题需注意的一点是开的数组应该从1到n而不是0到n-1,否则代码写起来很不方便。(其实这题最坑的地方还在于多组数据的输入。。。。题目明明写的是输入一组,但一组数据提交怎么都过不了!!!!!)
#include<iostream> #include<stdio.h> #include<algorithm> #define inf 1e9 #include<string.h> using namespace std; int dp[105][105]; int main() { int n; while(cin>>n) { memset(dp,0,sizeof(dp)); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { int a; cin>>a; dp[i][j]=dp[i][j-1]+a; } int max=-inf; for(int i=1;i<=n;i++) for(int j=i;j<=n;j++) { int s=0; for(int k=1;k<=n;k++) { if(s<0)s=0; s+=dp[k][j]-dp[k][i-1]; if(s>max) max=s; } } cout<<max<<endl; } return 0; }
在这里介绍方法2:
可能这一题不是特别适合方法2,不过在另外一些情况里面方法2可能会更优秀!
方法2是用每一个点存从最左上角的点到该点的矩阵的和,然后我们将计算子矩阵的复杂度降到了o(1),不过唯一的缺点就是要遍历所有点的组合,
这一题没有给n的范围,我试了试自己的方法感觉还行,事实上最大子矩阵的方法个人认为方法2更优。
#include <iostream> #include<string.h> using namespace std; int a[1155][1155]; int main() { int n; while(cin>>n) { int max0; memset(a,0,sizeof(a)); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) { int t;cin>>t; a[i][j]=a[i][j-1]+a[i-1][j]-a[i-1][j-1]+t; } max0=a[1][1]; for(int i=1;i<=n;i++) for(int j=i;j<=n;j++) for(int k=1;k<=n;k++) for(int l=k;l<=n;l++) if(a[j][l]-a[i-1][l]-a[j][k-1]+a[i-1][k-1]>max0) max0=a[j][l]-a[i-1][l]-a[j][k-1]+a[i-1][k-1]; cout<<max0<<endl; } return 0; }
持续更新博客地址:
blog.csdn.net/martinue