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;
    }
  • 相关阅读:
    链表中倒数第K个结点
    关于栈的经典问题---判断一个栈的出栈序列是不是有效的
    剑指Offer-用两个栈实现队列
    Netty与NIO
    牛客-反转数字
    N叉树的最大深度-DFS
    version can neither be null, empty nor blank
    剑指 Offer 16. 数值的整数次方
    Vue基础语法与指令
    ES6常用语法
  • 原文地址:https://www.cnblogs.com/chen9510/p/5270111.html
Copyright © 2011-2022 走看看