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.
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
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[]={,,,,,,,,,,,,};
int dir[][]={, ,, ,-, ,,-};
int dirs[][]={, ,, ,-, ,,-, -,- ,-, ,,- ,,};
const int inf=0x3f3f3f3f;
const ll mod=1e9+;
int n;
int sum[][];
int dp[];
int main(){
ios::sync_with_stdio(false);
while(cin>>n){
memset(sum,,sizeof(sum));
for(int i=;i<=n;i++)
for(int j=;j<=n;j++){
int t; cin>>t;
sum[i][j]=sum[i][j-]+t; //前缀和
}
int ans=-inf;
for(int i=;i<=n;i++)
for(int j=;j<=i;j++){ //二重循环枚举 把j~i压缩成一个点
int s=-inf;
memset(dp,,sizeof(dp));
for(int k=;k<=n;k++){ //找最大连续序列
dp[k]=max(dp[k-]+sum[k][i]-sum[k][j-],sum[k][i]-sum[k][j-]);
s=max(s,dp[k]);
}
ans=max(s,ans);
}
cout<<ans<<endl;
}
}