• 最大子矩阵


    网址: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;
    }
  • 相关阅读:
    面向对象三大特性之封装
    基本数据类型和引用数据类型
    面向对象三大特性之继承
    多表连接查询
    MySQL模糊查询
    MySQL数据查询入门
    Matlab 之 find()函数
    Matlab 之 字符串数组查找
    Matlab 之 数据元素访问
    让WIN10输入法变回传统模式
  • 原文地址:https://www.cnblogs.com/chen9510/p/5270111.html
Copyright © 2020-2023  润新知