zoukankan      html  css  js  c++  java
  • ZOJ1074 (最大和子矩阵 DP)

    F - 最大子矩阵和
    Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u
     

    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<iostream>
    #include<cstdio>
    #include<cstring>
    using namespace std;
    int n,sum,f,Max;
    int b[20000];
    int dp[150][150];
    int main()
    {
        f=-100;
        cin>>n;
        for(int i=0; i<n; i++)
            for(int j=0; j<n; j++)
            {
                cin>>dp[i][j];
            }
        for(int k=0; k<n; k++)
        {
            memset(b,0,sizeof(b));      // 一定每次记得清零
            for(int i=k; i<n; i++)
            {
                for(int j=0; j<n; j++)
                {
                    b[j]+=dp[i][j];
                }
                sum = Max =-100;         //赋很小的值
                for(int i=0; i<n; i++)
                {
                    if (sum<0)
                        sum = b[i];
                    else
                        sum += b[i];
                    if (Max < sum)
                        Max = sum;
                }
                if(f<Max)                  // 每次都要比较更新最大子矩阵和
                    f=Max;
            }
        }
        cout<<f<<endl;
    }



  • 相关阅读:
    现身说法“好奇心害死人啊”
    代码错误集合(全是低级错误,欢迎高手前来指教)
    Return from TAOKEE
    泡了DOUBAN一个下午,思考中。。。
    买了两本书
    PDFBox,PDF文件处理
    数据库营销,DM杂志
    一个JS写的时间选择显示的控件,源文件下载
    WEB2.0新想法,让明星还有你无所遁行,让你我都做“狗仔队”
    hdu 1237 简单计算器 (栈的简单应用)
  • 原文地址:https://www.cnblogs.com/hfc-xx/p/4728375.html
Copyright © 2011-2022 走看看