描述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.
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.输入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 500. The numbers in the array will be in the range [-127,127].输出Output the sum of the maximal sub-rectangle.样例输入
4 0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2
样例输出
15
题意:找出最大子矩阵和
题解:先考虑一维下的做法:
void maxx(){ int sum=-mod; rep(i,1,n){ if(sum>0)sum+=col[i]; else sum=col[i]; if(ans<sum)ans=sum; } }
那么在二维下,只需要将所有的行的状态都考虑进去,放入一个一维数组中即可
//#include<bits/stdc++.h> #include<algorithm> #include <iostream> #include <cstdlib> #include <cstring> #include <cassert> #include <cstdio> #include <vector> #include <string> #include <cmath> #include <queue> #include <stack> #include <set> #include <map> using namespace std; #define P(a,b,c) make_pair(a,make_pair(b,c)) #define rep(i,a,n) for (int i=a;i<=n;i++) #define per(i,a,n) for (int i=n;i>=a;i--) #define CLR(vis) memset(vis,0,sizeof(vis)) #define MST(vis,pos) memset(vis,pos,sizeof(vis)) #define pb push_back #define mp make_pair #define all(x) (x).begin(),(x).end() #define fi first #define se second #define SZ(x) ((int)(x).size()) typedef pair<int,pair<int,int> >pii; typedef long long ll; const ll mod = 1000000007; const int INF = 0x3f3f3f3f; ll gcd(ll a, ll b) { return b ? gcd(b, a%b) : a; } const int maxn = 1e3+5; int ma[maxn][maxn]; int col[maxn]; int n,ans=0; void maxx(){ int sum=-mod; rep(i,1,n){ if(sum>0)sum+=col[i]; else sum=col[i]; if(ans<sum)ans=sum; } } int main(){ scanf("%d", &n); rep(i,1,n) rep(j,1,n) scanf("%d", &ma[i][j]); rep(i,1,n){ memset(col,0,sizeof(col)); rep(j,i,n){ rep(k,1,n){ col[k]+=ma[j][k]; } maxx(); } } cout<<ans; return 0; } //可看作一行,但是列举所有情况,即列举不同的行数的和