首页 > 代码库 > Timus 1146. Maximum Sum
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 |
---|---|
40 -2 -7 09 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 :guanjunCreated Time :2016/10/7 13:50:13File 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。