1002. 二哥种花生——java

Description

二哥在自己的后花园里种了一些花生,也快到了收获的时候了。这片花生地是一个长度为L、宽度为W的矩形,每个单位面积上花生产量都是独立的。他想知道,对于某个指定的区域大小,在这么大的矩形区域内,花生的产量最大会是多少。

Input Format

第1行有2个整数,长度L和宽度W。

第2行至第L+1行,每行有W个整数,分别表示对应的单位面积上的花生产量A( 0A<10 )。

第L+2行有2个整数,分别是指定的区域大小的长度a和宽度b。

Output Format

输出一个整数m,表示在指定大小的区域内,花生最大产量为m。

Sample Input

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

Sample Output

38

样例解释

左上角:38 = (1+2+3) + (6+7+8) + (0+9+2)

数据范围

对于30%的数据: 1L,W100

对于100%的数据: 1L,W1000

全部区域大小满足:1aL1bW 。

这道题可以说是一道挑战你的极限的题,各种超时。

但是不得不承认,这是一道经典的卡时间的题,妈的。提交了10次超时9次、、、、、

从最开始的简单的四重循环,到最终的通过,真心是改了不少啊,不过也发现了自己一个缺点,想问题一次思考不完全,不能完全想到最短时间的方法。下面是源代码。

import java.util.Scanner;
public class Main {
	private static Scanner in;
	public static void main(String[] args) {
		in = new Scanner(System.in);
		int L = in.nextInt();
		int W = in.nextInt();
		int [][]s = new int [L][W];
		for(int i=0;i<L;i++){
			for(int j=0;j<W;j++){
				s[i][j]=in.nextInt();
			}
		}
		int sum=0;
		int res=0;
		int a=in.nextInt();
		int b=in.nextInt();
		int e[]=new int [W];
		int c=0;
		int count =b;
		for(int i=0;i<=L-a;i++){
			for(int j=0;j<=W-b;j++){
				if(i==0&&j==0){
					for(int k=0;k<b;k++){
						for(int t =0;t<a;t++){
							e[k]+=s[t][k];
						}
						sum+=e[k];
					}
				}else if(j==0&&i!=0){
					for(int k=0;k<b;k++){
						e[k]=e[k]-s[i-1][k]+s[i+a-1][k];
						c = c+e[k];
					}
					sum=c;
					c=0;
				}else{
					if(i==0){
						for(int h=i;h<i+a;h++){
							e[count]+=s[h][j+b-1];
						}
						sum = sum+e[count]-e[count-b]; 
						count ++;
					}else{
						e[j+b-1]=e[j+b-1]-s[i-1][j+b-1]+s[i+a-1][j+b-1];
						sum = sum+e[j+b-1]-e[j-1];
					}
				}
				if(res<sum){
					res =sum;
				}
			}
		}
		System.out.println(res);
	}
}

 发现测试数据

4 5
1 2 3 4 5
6 7 8 0 0
0 9 2 2 3
3 0 0 0 1
3 3
并不能反映很多问题,建议使用如下测试数据
4 5
1 2 3 4 5
6 7 8 9 0
0 9 2 2 3
3 0 0 0 1
2 3
输出37


原文地址:https://www.cnblogs.com/969059506-java/p/3780954.html