zoukankan      html  css  js  c++  java
  • To the max(求最大子矩阵和)

    To the Max
    Time Limit: 1000MS   Memory Limit: 10000K
    Total Submissions: 47985   Accepted: 25387

    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^6完全不可取

    前缀和优化枚举:分别搜一个左上角的点和一个右上角的点,可以将复杂度降到n^4,但仍然超时

    于是我们考虑,可不可以换一种思路:

    可以枚举上下边界,然后问题就转变成了一位字段和求最大

    #include<iostream>
    using namespace std;
    int n,map[200][200],sum[200][200],ans;
    int main(){
        cin>>n;
        for(int i=1;i<=n;i++)
            for(int j=1;j<=n;j++){
                cin>>map[i][j];
                sum[i][j]=sum[i][j-1]+map[i][j];
            }
        for(int i=1;i<n;i++){
            for(int j=i;j<=n;j++){
                int Sum=0;
                for(int k=1;k<=n;k++){
                    Sum+=sum[k][j]-sum[k][i-1];
                    if(Sum<0)Sum=0;
                    else if(Sum>ans)ans=Sum;
                }
            }
        }
        cout<<ans;
    }
       
    
    
  • 相关阅读:
    体验ASP.NET 2.0中的BuildProvider(转载)
    为什么要用非关系数据库?
    Inside ASP.NET 2.0即时编译系统(转载)
    文本信息检索(维基百科)
    通用数据压缩算法简介
    在HttpModule中使用gzip,deflate协议对aspx页面进行压缩
    NoSQL非关系型数据库
    fatal error C1001: INTERNAL COMPILER ERROR (compiler file 'msc1.cpp', line 1786)
    C++中的变量 Variables in C++
    Visual C++, pow(),error C2065: 'pow' : undeclared identifier
  • 原文地址:https://www.cnblogs.com/thmyl/p/7359318.html
Copyright © 2011-2022 走看看