To The Max(动态规划)

来源:互联网 发布:华为交换机 端口详解 编辑:程序博客网 时间:2024/06/05 06:00

To The Max
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13511 Accepted Submission(s): 6443

Problem 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 -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 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 -2

Sample Output

15

这道题就是一个二维数组压缩成一个一维的 然后在按照一维数组的求最大连续子序列的和一样的
比如说题目当中的例子
0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
当fun n 和 m 分别为2 4 时
tmp数组此时就是存储的将
9 2 -6 2
-4 1 -4 1
-1 8 0 -2
压缩成
tmp[1] = 9-4-1 = 4
tmp[2] = 2+1+8= 11
tmp[3] = -6 -4 +0 = 10
tmp[4] = 2 + 1-2 = 1
然后在按照最长连续子序列和呢样算就行了

#include<iostream>#include<stdio.h>#include<string.h>using namespace std;int sum[102],mp[102][102],tmp[102];int N;int fun(int n,int m){    memset(sum,0,sizeof(sum));    memset(tmp,0,sizeof(tmp));    for(int i = 1;i<=N;i++)    {        for(int j = n;j<=m;j++)//压缩矩阵 我们要让二维变成一维 故需要让列当做横坐标这样就是一个一维的了        {            tmp[i] +=mp[j][i];        }    }    int mx = - 99999;    for(int i =1;i<=N;i++)//求最大连续子矩阵的和转化为一维求最大连续子序列的和    {        if(sum[i-1]<0)            sum[i] = tmp[i];        else            sum[i] =sum[i-1] + tmp[i];        if(sum[i]>mx)            mx = sum[i];    }    return mx;}int main(){    while(~scanf("%d",&N))    {        for(int i =1;i<=N;i++)        {            for(int j =1;j<=N;j++)            {                scanf("%d",&mp[i][j]);            }        }        int mx = 0;        for(int i =1;i<=N;i++)        {            for(int j = i;j<=N;j++)//划分成小矩形            {                int tt = fun(i,j);                if(tt>mx)                    mx = tt;            }        }        printf("%d\n",&mx);    }    return 0;}
原创粉丝点击