Timus 1146. Maximum Sum
Posted いいえ敗者
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Timus 1146. Maximum Sum相关的知识,希望对你有一定的参考价值。
1146. Maximum Sum
Time limit: 0.5 second
Memory limit: 64 MB
Memory limit: 64 MB
Given a 2-dimensional array of positive and negative integers, find the sub-rectangle with the largest sum. 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. A sub-rectangle is any contiguous sub-array of size 1 × 1 or greater located within the whole array.
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-hand corner and has the sum of 15.
Input
The input consists of an N × N array of integers. The input begins with a single positive integerN on a line by itself indicating the size of the square two dimensional array. This is followed byN 2 integers separated by white-space (newlines and spaces). These N 2 integers make up the array in row-major order (i.e., all numbers on the first row, left-to-right, then all numbers on 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
The output is the sum of the maximal sub-rectangle.
Sample
input | output |
---|---|
4 0 -2 -7 0 9 2 -6 2 -4 1 -4 1 -1 8 0 -2 |
15 |
最大子矩阵。很经典的问题哈哈
压缩 然后最大连续子序列 dp[i]=dp[i-1]<0?a[i]:dp[i-1]+a[i]
一开始压缩的时候没用前缀和,n^4 貌似过不了,后来用前缀和优化到n^3
下面代码中dp 的空间也可以优化,这里没有优化.
/* *********************************************** Author :guanjun Created Time :2016/10/7 13:50:13 File Name :timus1146.cpp ************************************************ */ #include <bits/stdc++.h> #define ull unsigned long long #define ll long long #define mod 90001 #define INF 0x3f3f3f3f #define maxn 10010 #define cle(a) memset(a,0,sizeof(a)) const ull inf = 1LL << 61; const double eps=1e-5; using namespace std; priority_queue<int,vector<int>,greater<int> >pq; struct Node{ int x,y; }; struct cmp{ bool operator()(Node a,Node b){ if(a.x==b.x) return a.y> b.y; return a.x>b.x; } }; bool cmp(int a,int b){ return a>b; } int a[110][110],n; int sum[110][110]; int dp[110]; int main() { #ifndef ONLINE_JUDGE //freopen("in.txt","r",stdin); #endif //freopen("out.txt","w",stdout); while(scanf("%d",&n)!=EOF){ cle(sum); for(int i=1;i<=n;i++){ for(int j=1;j<=n;j++){ scanf("%d",&a[i][j]); sum[i][j]=sum[i][j-1]+a[i][j]; } } int Max=-INF; //dp 求最大连续子序列 dp[i]代表以i为结尾的最大连续子序列的长度 for(int i=1;i<=n;i++){ for(int j=1;j<=i;j++){ cle(dp); for(int k=1;k<=n;k++){ int tmp=sum[k][i]-sum[k][j-1]; if(dp[k-1]<0){ dp[k]=tmp; } else dp[k]=tmp+dp[k-1]; Max=max(dp[k],Max); } } } cout<<Max<<endl; } return 0; }
以上是关于Timus 1146. Maximum Sum的主要内容,如果未能解决你的问题,请参考以下文章
Binary Tree Maximum Path Sum 自底向上求解(重重重重)
第四周 Leetcode 124. Binary Tree Maximum Path Sum (HARD)