我是靠谱客的博主 光亮滑板,最近开发中收集的这篇文章主要介绍POJ- 1050- to the Max 【动态规划】,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

To the Max

Time Limit: 1000MS Memory Limit: 10000K
Total Submissions: 52276 Accepted: 27629

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列的和,然后用sum[k][j]-sun[k][i-1],就说明第k行第i列到第j列的和。具体见代码:

AC:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<climits>
using namespace std;
const int maxn=101;
int arr[maxn][maxn]={0},sum[maxn][maxn]={0};
int main(void){
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>arr[i][j];
sum[i][j]=sum[i][j-1]+arr[i][j]; //记录每一行前j列的和
}
}
int max=INT_MIN,temp;//max初始化为整数最小值
for(int i=1;i<=n;i++){ //列
for(int j=i;j<=n;j++){ //列
temp=0;
for(int k=0;k<=n;k++){ //行
if(temp<0) temp=0;
temp+=sum[k][j]-sum[k][i-1];
if(temp>max) max=temp; //一旦有比之前的最大值就取代记录
}
}
}
printf("%dn",max);
return 0;
}

 

最后

以上就是光亮滑板为你收集整理的POJ- 1050- to the Max 【动态规划】的全部内容,希望文章能够帮你解决POJ- 1050- to the Max 【动态规划】所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(51)

评论列表共有 0 条评论

立即
投稿
返回
顶部