FOJ 1018 Maximal Sum(三维子矩最大和)

三维数组最大子立方和
本文介绍了一种解决三维数组中寻找最大子立方和的方法,通过动态规划算法实现了高效的求解过程。该算法首先对输入的三维数组进行预处理,然后通过多层循环遍历并计算所有可能的子立方的最大和。
Problem Description

Given a cube of positive and negative integers, find the sub-cube with the largest sum. The sum of a cube is the sum of all the elements in that cube. In this problem, the sub-cube with the largest sum is referred to as the maximal sub-cube.

A sub-cube is any contiguous sub-array of size 1 x 1 x 1 or greater located within the whole array.

As an example, if a cube is formed by following 3 x 3 x 3 integers:

0 -1 3
-5 7 4
-8 9 1
-1 -3 -1
2 -1 5
0 -1 3
3 1 -1
1 3 2
1 -2 1

Then its maximal sub-cube which has sum 31 is as follows:

7 4
9 1
-1 5
-1 3
3 2
-2 1

Input

Each input set consists of two parts. The first line of the input set is a single positive integer N between 1 and 20, followed by N x N x N integers separated by white-spaces (newlines or spaces). These integers make up the array in a plane, row-major order (i.e., all numbers on the first plane, first row, left-to-right, then the first plane, second row, left-to-right, etc.). The numbers in the array will be in the range [-127,127].

The input is terminated by a value 0 for N.

Output

The output is the sum of the maximal sub-cube.

Sample Input

3
0 -1 3
-5 7 4
-8 9 1
-1 -3 -1
2 -1 5
0 -1 3
3 1 -1
1 3 2
1 -2 1
0

Sample Output

31

 

本题是三维的,建议先从一维做起,http://acm.nyist.edu.cn/JudgeOnline/problem.php?pid=44

二维 的:http://poj.org/problem?id=1050

直接贴代码,很简单的题

 

AC代码:
 

 

# include <stdio.h> 
# include <string.h>
# include <limits.h>
# include <algorithm>
using namespace std;
int a[30][30][30];
int s[30][30][30], area[30][30][30];
int dp[30];
int main(){
	int i, j, k, l, m, n, d, g_max, l_max;
	while(scanf("%d", &n)){
		if(n==0){
			break;
		}
		g_max=INT_MIN;
		memset(s, 0, sizeof(s));
		for(i=1; i<=n; i++){
			for(j=1; j<=n; j++){
				for(k=1; k<=n; k++){
					scanf("%d", &a[i][j][k]);
					s[i][k][j]=s[i][k][j-1]+a[i][j][k];
				}
			}
		}
		for(k=1; k<=n; k++){
			for(l=k; l<=n; l++){
				for(m=1; m<=n; m++){
					memset(area, 0, sizeof(area));
					for(j=m; j<=n; j++){
						l_max=INT_MIN;
						for(i=1; i<=n; i++){
							area[i][m][j]=area[i][m][j-1]+s[i][j][l]-s[i][j][k-1];
						}
						dp[0]=0;
						for(i=1; i<=n; i++){
							dp[i]=max(area[i][m][j], dp[i-1]+area[i][m][j]);
							if(dp[i]>l_max){
								l_max=dp[i];
							}
						}
						if(l_max>g_max){
							g_max=l_max;
						}
					}
				}
			}
		}
		printf("%d\n", g_max);
	}
	return 0;
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值