[POJ1050]To the Max

[POJ1050]To the Max

试题描述

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. 

输入

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 the sum of the maximal sub-rectangle.

输入示例

4
0 -2 -7 0 9 2 -6 2
-4 1 -4  1 -1

8  0 -2

输出示例

15

数据规模及约定

见“输入

题解

预处理前缀和,然后 O(n4) 大暴力。

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <stack>
#include <vector>
#include <queue>
#include <cstring>
#include <string>
#include <map>
#include <set>
using namespace std;

const int BufferSize = 1 << 16;
char buffer[BufferSize], *Head, *Tail;
inline char Getchar() {
    if(Head == Tail) {
        int l = fread(buffer, 1, BufferSize, stdin);
        Tail = (Head = buffer) + l;
    }
    return *Head++;
}
int read() {
    int x = 0, f = 1; char c = getchar();
    while(!isdigit(c)){ if(c == '-') f = -1; c = getchar(); }
    while(isdigit(c)){ x = x * 10 + c - '0'; c = getchar(); }
    return x * f;
}

#define maxn 110
int n, S[maxn][maxn];

int main() {
	n = read();
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= n; j++) S[i][j] = S[i-1][j] + S[i][j-1] - S[i-1][j-1] + read();
	
	int ans = 0;
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= n; j++)
			for(int x = i; x <= n; x++)
				for(int y = j; y <= n; y++) {
					ans = max(ans, S[x][y] - S[i-1][y] - S[x][j-1] + S[i-1][j-1]);
				}
	
	printf("%d\n", ans);
	
	return 0;
}

 

posted @ 2016-08-28 14:19  xjr01  阅读(211)  评论(0编辑  收藏  举报