POJ1050 求最大子矩阵和

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. 

 

描述为英语,大概意思就是求一个N*N的矩阵的最大子矩阵和

 

无从下手,看了一些大佬们的代码思路,学习了降维思想。可以讲二维多行合并成一行降成一维。

我们先求一维数组的最大子数组和。思路如下:其实就是动态规划

    假如之前累加的结果大于零,则继续累加。否则从下一个位置开始累加。每次判断是否是最大值。即是

temp=max(temp,     temp+m[i](if(temp>0))    )

 

求一维数组最大累加和代码如下

package com.luo;

import java.util.Scanner;

public class Temp {

	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		while(in.hasNextInt()){
			int len=in.nextInt();
			int[] input=new int[len];
			for(int i=0;i<len;i++){
				input[i]=in.nextInt();
			}
			int max=0;
			int temp=0;
			for(int i=0;i<len;i++){
				if(temp>0)
					temp+=input[i];
				else
					temp=input[i];
				if(temp>max)
					max=temp;
			}
			
			System.out.println("最大字段和为:"+max);
		}
	}
}

 

    如何将一维拓展到二维呢。多行合并成一行。要进行合并的行数很多,两行合并成一行,三行合并成一行,四行合并成一行...   这样子不会造成数据重叠吗。

    其实这是可以避免的,我们从第一行开始,这时候需要将第一行第二行合并成一行计算最大矩阵,接着合并第一二三行计算最大矩阵,再接着合并第一二三四行计算最大矩阵... 合并完所有包括第一行的矩阵后第一行被合并的情况已经被全部考虑了,这时候不需要第一行了

所以代码如下:

package com.luo.daily;

import java.util.Scanner;

public class Poj1050 {

	public static void main(String[] args) {
		Scanner in=new Scanner(System.in);
		while(in.hasNextInt()){
			int N=in.nextInt();
			int[][] input=new int[N][N];
			int max=0;
			int temp=0;
			for(int i=0;i<N;i++){
				for(int j=0;j<N;j++){
					input[i][j]=in.nextInt();  //输入顺便计算每行的最大子数组和
					if(temp>0)
						temp+=input[i][j];
					else
						temp=input[i][j];
					if(temp>max)
						max=temp;
				}
			}
			for(int i=0;i<N-1;i++){
				for(int j=i+1;j<N;j++){
					temp=0;
					for(int k=0;k<N;k++){
						input[i][k]+=input[j][k];
						if(temp>0)
							temp+=input[i][k];
						else
							temp=input[i][k];
						if(temp>max)
							max=temp;
					}
				}
			}
			System.out.println("最大的子矩阵和为:"+max);
			
		}
	}
}

 

 

转载于:https://my.oschina.net/u/2254579/blog/884262

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值