To The Max_hdu_1081(经典DP).java
To The Max
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 6815 Accepted Submission(s): 3270
Problem Description
Given a two-dimensional array of positive and negative integers, a sub-rectangle is any contiguous sub-array of size 1 x 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 x 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
Source
Greater New York 2001
Recommend
We have carefully selected several similar problems for you: 1024 1025 1080 1074 1059
[java]
import java.io.InputStreamReader;
import java.util.Scanner;
public class Main{//经典dp
public static void main(String[] args) {
Scanner input=new Scanner(new InputStreamReader(System.in));
while(input.hasNext()){
int n=input.nextInt();
int a[][]=new int[n+1][n+1];
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
a[i][j]=a[i][j-1]+input.nextInt(); //表示第i行前j个元素之和
}
}
int max=-999;
for(int i=1;i<=n;i++){
for(int j=i;j<=n;j++){
int sum=0;
for(int k=1;k<=n;k++){
if(sum<0)
sum=0;
sum+=a[k][j]-a[k][i-1];//计算第k行第j和第i列之间的的数
if(sum>max)
max=sum;
}
}
}
System.out.println(max);
}
}
}
[cpp]
#include"stdio.h"
#include"string.h"
int main()
{
int num[105][105];
int i1,i2,i_temp,l;
int temp[105];
int n;
int max;
int temp0;
while(scanf("%d",&n)!=-1)
{
for(i1=0;i1<n;i1++)
for(l=0;l<n;l++)
scanf("%d",&num[i1][l]);
max=0;
for(i2=0;i2<n;i2++)
{
for(i1=0;i1<=i2;i1++)
{
/*****/ //压缩
for(l=0;l<n;l++)
{
temp0=0;
for(i_temp=i1;i_temp<=i2;i_temp++) temp0+=num[i_temp][l];
temp[l]=temp0;
}
/*****/
if(temp[0]>max) max=temp[0];
for(l=1;l<n;l++)
{
if(temp[l-1]>0) temp[l]+=temp[l-1];
if(temp[l]>max) max=temp[l];
}
}
}
printf("%d\n",max);
}
return 0;
}
[cpp]
#include<iostream>
using namespace std;
int a[101][101];
int main()  
补充:软件开发 , C++ ,