【POJ - 1050】To the Max (dp)
題干:
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.?
Input
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 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解題報告:
給一個N*N的矩陣,求最大子矩陣和。
AC代碼1:(o(n^4)的復雜度)
#include<cstdio> using namespace std; int main() {int c,res=0,k;int d[100][100];int s[101],a[100];while(scanf("%d",&c)==1) {for(int i=0; i<c; i++) {for(int j=0; j<c; j++) {scanf("%d",&d[i][j]);}}for(int i=0; i<c; i++) {for(int j=(i+1); j<c; j++) {for(int l=0; l<100; l++) {a[l]=0;s[l]=0;}for(k=0; k<c; k++) {for(int m=i; m<=j; m++)a[k]+=d[m][k];if(s[k]>=0)s[k+1]=s[k]+a[k];elses[k+1]=a[k];}for(int i=0; i<k; i++) {if(res<s[i])res=s[i];}}}printf("%d",res);} }AC代碼2:(o(n^3)的復雜度)
#include<cstdio> #include<cstring> #include<algorithm> using namespace std; int maze[105][105]; int sum[105],tmp[105]; int main() {int n;int maxx = 0;scanf("%d",&n);memset(sum,0,sizeof sum);for(int i = 1; i<=n; i++) {for(int j = 1; j<=n; j++) {scanf("%d",&maze[i][j]);if(sum[i-1] >=0) sum[i] = sum[i-1] + maze[i][j];else sum[i] = maze[i][j];maxx = max(maxx,sum[i]);}}//上面內容表示單行的最大字段和 for(int i = 1; i<=n; i++) {for(int j = 1; j<=n; j++) tmp[j] = maze[i][j];for(int j = i+1; j<=n; j++) {memset(sum,0,sizeof sum);for(int k = 1; k<=n; k++) {tmp[k] += maze[j][k];if(sum[k-1] >=0) sum[k] = sum[k-1] + tmp[k];else sum[k] = tmp[k];maxx = max(maxx,sum[k]); }}} printf("%d\n",maxx);return 0 ; }?
總結
以上是生活随笔為你收集整理的【POJ - 1050】To the Max (dp)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【CodeForces - 599C 】
- 下一篇: 【LeetCode - 33】搜索旋转排