POJ 1050 To the Max 二维最大子段和

To the Max
Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 52281 Accepted: 27633
Description

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 -2
Sample Output

15

题意:给你一个n*n 的矩形,要你求和最大的一个子矩形
题解:由一维的最大子段和变成了二维的最大子矩阵和,思想还是一样的,那就是保存每一段的最大和,然后更新最大值就行
将二维的看做一维,即控制第二维的深度去求最大子段和
代码如下:

#include <map>
#include <set>
#include <cmath>
#include <ctime>
#include <stack>
#include <queue>
#include <cstdio>
#include <cctype>
#include <bitset>
#include <string>
#include <vector>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <functional>
#define fuck(x) cout<<"["<<x<<"]";
#define FIN freopen("input.txt","r",stdin);
#define FOUT freopen("output.txt","w+",stdout);
//#pragma comment(linker, "/STACK:102400000,102400000")
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int maxn = 1e3+5;
const int INF = 0x3f3f3f3f;
int dp[maxn];
int mp[maxn][maxn];
int maxx;


int main(){
#ifndef ONLINE_JUDGE
    FIN
#endif
    int n;
    scanf("%d",&n);
    maxx=-1;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=n;j++){
            scanf("%d",&mp[i][j]);
            if(mp[i][j]>maxx){
                maxx=mp[i][j];
            }
        }
    }
    if(maxx<=0){
        printf("%d\n",maxx);
    }else{
        maxx=-1;
        int l,r;
        for(int i=1;i<=n;i++){
            for(int j=1;j<=n-i+1;j++){  //控制所求子段的深度
                l=i,r=j+i-1;
                dp[0]=0;
                for(int k=1;k<=n;k++){            //控制所求子段的长度
                    int tmp=0;
                    for(int s=l;s<=r;s++){
                        tmp+=mp[k][s];
                    }
                    dp[k]=max(dp[k-1]+tmp,tmp);
                    maxx=max(dp[k],maxx);
                }
            }
        }
        printf("%d\n",maxx);
    }
    return 0;
}
View Code

 

posted @ 2018-08-06 16:25  buerdepepeqi  阅读(156)  评论(0编辑  收藏  举报