• 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;
    }
    
    
  • 相关阅读:
    PHPStorm 2018 的安装 汉化 与使用
    aptana怎么显示空格 tab和回车等
    学习linux—— VMware 安装 ubantu 18 如何连接wifi
    [转]MAC系统下Sublime Text3 配置Python3详细教程(亲测有效)
    如何利用sql 读取辅表的最大max 和第二最大max。。。。
    利用PHPExcel导出excel 以及利用js导出excel
    yii2.0如何优化路由
    教女朋友写第一个php,php环境配置
    js 删除数组中的某一个内容
    vue 路由守卫是否携带token
  • 原文地址:https://www.cnblogs.com/thmyl/p/6362669.html
Copyright © 2020-2023  润新知