PolarisSherlock

导航

poj1050

To the Max
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 39081   Accepted: 20639

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
 1 /* 
 2  * File:   main.cpp
 3  * Author: liaoyu <liaoyu@whu.edu.cn>
 4  *
 5  * Created on April 1, 2014, 5:34 PM
 6  */
 7 
 8 #include <iostream>
 9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <cmath>
13 #include <algorithm>
14 using namespace std;
15 
16 int a[105][105];
17 
18 int maxSubArray(int n, int* a)
19 {
20     int max = 0x80000000;
21     int b = a[0];
22     for (int i = 1; i < n; i++) {
23         if (b > 0)b += a[i];
24         else b = a[i];
25         if (b > max)max = b;
26     }
27     return max;
28 }
29 int b[105];
30 
31 int main()
32 {
33     int n;
34     scanf("%d", &n);
35     int max = 0x80000000;
36     for (int i = 0; i < n; i++)
37         for (int j = 0; j < n; j++)
38             scanf("%d", &a[i][j]);
39     for (int i = 0; i < n; i++)
40         for (int j = i; j < n; j++) {
41             for (int l = 0; l < n; l++) {
42                 b[l] = 0;
43                 for (int k = i; k <= j; k++) {
44                     b[l] += a[l][k];
45                 }
46             }
47             int tmp = maxSubArray(n, b);
48             if (tmp > max)max = tmp;
49         }
50     printf("%d\n", max);
51 }
View Code

 

 

posted on 2014-04-06 19:17  PolarisSherlock  阅读(118)  评论(0编辑  收藏  举报