程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> ZOJ1074 (最大和子矩陣 DP),zoj1074dp

ZOJ1074 (最大和子矩陣 DP),zoj1074dp

編輯:C++入門知識

ZOJ1074 (最大和子矩陣 DP),zoj1074dp


F - 最大子矩陣和 Time Limit:1000MS     Memory Limit:10000KB     64bit IO Format:%I64d & %I64u  

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行。
然後從第二行開始,按照上面的進行,再從第三行開始..... 直到第n行....
每次都要更新他們的子矩陣的的最大值,用一個變量更新
不說了,上代碼,最下面有輸出截圖
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int n,sum,f,Max;
int b[20000];
int dp[150][150];
int main()
{
    f=-100;
    cin>>n;
    for(int i=0; i<n; i++)
        for(int j=0; j<n; j++)
        {
            cin>>dp[i][j];
        }
    for(int k=0; k<n; k++)
    {
        memset(b,0,sizeof(b));      // 一定每次記得清零
        for(int i=k; i<n; i++)
        {
            for(int j=0; j<n; j++)
            {
                b[j]+=dp[i][j];
            }
            sum = Max =-100;         //賦很小的值
            for(int i=0; i<n; i++)
            {
                if (sum<0)
                    sum = b[i];
                else
                    sum += b[i];
                if (Max < sum)
                    Max = sum;
            }
            if(f<Max)                  // 每次都要比較更新最大子矩陣和
                f=Max;
        }
    }
    cout<<f<<endl;
}



  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved