zoukankan      html  css  js  c++  java
  • 最大子矩阵

    网址:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=67090#problem/B

    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

    解题思路: 以i,j为循环层,temp[k]表示从i行到j行第k列的和,然后求temp[]数组序列的最大连续子列的最大和。
    #include <iostream>
    #include <algorithm>
    #include <cstring>
    #include <cstdio>
    #include <stack>
    using namespace std;
    #define INF 0x3f3f3f3f
    int a[110][110];
    int temp[110];
    
    int main()
    {
        int n;
        int MAX;
        while(scanf("%d",&n)!=EOF)
        {
            MAX=-1*INF;
            for(int i=0;i<n;i++)
            for(int j=0;j<n;j++)
            scanf("%d",&a[i][j]);
            for(int i=0;i<n;i++)
            {
                memset(temp,0,sizeof(temp));
                for(int j=i;j<n;j++)
                {
                    for(int k=0;k<n;k++)
                        temp[k]+=a[j][k];//从i行到j行的每一列的和;
                    int s=0;
                    for(int k=0;k<n;k++)//数组temp[]的最大连续子列的最大和;
                     {
                         if(s<0) s=0;
                         s=s+temp[k];
                         if(MAX<s) MAX=s;
                     }
                }
            }
            printf("%d
    ",MAX);
        }
        return 0;
    }
  • 相关阅读:
    梯度下降算法 (转)
    机器学习
    杭电1097-A hard puzzle
    动态规划初步习题(紫书)
    4.21考试题解
    【bzoj4445 scoi2015】小凸想跑步
    【bzoj4444 scoi2015】国旗计划
    【bzoj4443 scoi2015】小凸玩矩阵
    【luogu P4007 清华集训2017】小Y和恐怖奴隶主
    【luoguP4006 清华集训2017】小Y和二叉树
  • 原文地址:https://www.cnblogs.com/chen9510/p/5270111.html
Copyright © 2011-2022 走看看