hdu 1081 To The Max(二维压缩的最大连续序列)(最大矩阵和)
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
题意:求n*n的矩阵里和最大的子矩阵。
最大连续序列和找最大和矩阵有着共通点,这里需要把一维的转化为二维的是关键
我们可以假定把每一行看作单个的元素,知道每个元素的值,那我们就能够将n列,看作有n个这样的压缩元素,那我们就是在这n个元素中找最大值
(当然压缩列也是可以的,这里我的代码写的是压缩行)
那么我们转化成用二维的sum[i][j]来维护前缀和,表示第i行前j个数的和
#include <cstdio> #include <map> #include <iostream> #include<cstring> #include<bits/stdc++.h> #define ll long long int #define M 6 using namespace std; inline ll gcd(ll a,ll b){return b?gcd(b,a%b):a;} inline ll lcm(ll a,ll b){return a/gcd(a,b)*b;} int moth[13]={0,31,28,31,30,31,30,31,31,30,31,30,31}; int dir[4][2]={1,0 ,0,1 ,-1,0 ,0,-1}; int dirs[8][2]={1,0 ,0,1 ,-1,0 ,0,-1, -1,-1 ,-1,1 ,1,-1 ,1,1}; const int inf=0x3f3f3f3f; const ll mod=1e9+7; int n; int sum[107][107]; int dp[107]; int main(){ ios::sync_with_stdio(false); while(cin>>n){ memset(sum,0,sizeof(sum)); for(int i=1;i<=n;i++) for(int j=1;j<=n;j++){ int t; cin>>t; sum[i][j]=sum[i][j-1]+t; //前缀和 } int ans=-inf; for(int i=1;i<=n;i++) for(int j=1;j<=i;j++){ //二重循环枚举 把j~i压缩成一个点 int s=-inf; memset(dp,0,sizeof(dp)); for(int k=1;k<=n;k++){ //找最大连续序列 dp[k]=max(dp[k-1]+sum[k][i]-sum[k][j-1],sum[k][i]-sum[k][j-1]); s=max(s,dp[k]); } ans=max(s,ans); } cout<<ans<<endl; } }