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

    最大子矩阵和

    题目链接:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=87125#problem/F

     题目:

        

    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

    题意:
    求矩阵中和最大的小矩阵,输出该和。
    分析:
    把第j列前i个数的和放入a[i][j]中,求第i行到第j行之间的最大和矩阵的时候,就以i行和j行之间的同一列的数字的和为累加数字进行比较,然后dp求这个数列的最大和连续子序列。
     1 #include<iostream> 
     2 #include<cstring>  
     3 using namespace std;
     4 int a[105][105];
     5 int main()
     6 {
     7     int n,i,j,x,Max;
     8    while(cin>>n)
     9    {  
    10       Max=0;
    11     memset(a,0,sizeof(a));
    12     for(i=1;i<=n;i++)
    13     {
    14         for(j=1;j<=n;j++)
    15         {   
    16             cin>>x;
    17          a[i][j]=a[i-1][j]+x;
    18         }
    19     }
    20     for(i=1;i<=n;i++)
    21     {  
    22         for(j=i;j<=n;j++)
    23         {
    24            int    sum=0;
    25             for(int k=1;k<=n;k++)
    26             {
    27               x=a[j][k]-a[i-1][k];
    28               sum=sum+x;
    29               if(sum>Max)
    30                   Max=sum;
    31               if(sum<0)  sum=0;
    32             }
    33           }    
    34     }
    35    cout<<Max<<endl;
    36 }
    37     return 0;
    38  }
  • 相关阅读:
    java 利用jsoup 爬取知乎首页问题
    ROIAlign, ROIPooling及ROIWarp对比
    yii2.0 gii
    mysql索引操作
    lbs basic mongodb
    php操作mongodb
    设计模式六大原则
    Java集合
    Java 快速失败( fail-fast ) 安全失败( fail-safe )
    计数数组中值的出现次数
  • 原文地址:https://www.cnblogs.com/fenhong/p/4724796.html
Copyright © 2011-2022 走看看