题目
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 -2is in the lower left corner:
9 2
-4 1
-1 8and 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 -2Sample Output
15
题解
题目让求最大的矩形区域的权值和
不看二维,单看一维,就是最大连续子序列
dp[i] = max(dp[i-1]+a[i] , a[i])
而拓展到二维,可以先将它压缩成一维
用 O(n2) 的时间遍历取起始行和终止行,将其压缩成一行
用 O(n) 的时间复杂付求取最大连续子序列
最终总的时间复杂度是 O(n3)
代码
/* By:OhYee Github:OhYee Blog:http://www.oyohyee.com/ Email:oyohyee@oyohyee.com かしこいかわいい? エリーチカ! 要写出来Хорошо的代码哦~ */ #include <cstdio> #include <algorithm> #include <cstring> #include <cmath> #include <string> #include <iostream> #include <vector> #include <list> #include <queue> #include <stack> #include <map> #include <set> #include <functional> using namespace std; const int INF = 0x7FFFFFFF; const int maxn = 105; const int delta[] = {1,-1,0,0}; int Map[maxn][maxn]; int dp[maxn]; int sum[maxn][maxn]; int n; int DP(int s,int v) { int Max = -INF; for(int i = 1;i <= n;i++) { int t = sum[v][i] - sum[s][i]; dp[i] = max(dp[i - 1] + t,t); Max = max(Max,dp[i]); } return Max; } bool Do() { if(scanf("%d",&n) == EOF) return false; for(int i = 1;i <= n;i++) for(int j = 1;j <= n;j++) { scanf("%d",&Map[i][j]); sum[i][j] = sum[i - 1][j] + Map[i][j]; } int Max = -INF; for(int i = 1;i <= n;i++) for(int j = 0;j < i;j++) { Max = max(Max,DP(j,i)); } printf("%d\n",Max); return true; } int main() { while(Do()); return 0; }