nyoj 102 最大和

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=104


题目大意:这个题是二维连续子矩阵的最大和,是 子串和 的升级版。


解题思路:枚举每个子矩阵,求出子矩阵的和,并笔记录最大值


解题技巧:像这类的连续和,这里有一个小技巧:(input:a[0],a[1],a[2],...,a[n])映射到(handle:s[0],s[1],s[2],...,s[n]),就不必重复计算加和了

    上码更清晰:

import java.io.BufferedInputStream;

public class _104 {
	static int[][] arr = new int[5][5];
	static BufferedInputStream bis = new BufferedInputStream(System.in);

	public static void main(String[] args) throws Exception {
		int nCase, row, col, max;
		nCase = getInt();
		while (nCase-- != 0) {
			row = getInt();//优化int的读入,但是跟sc.hasNext()配合使用,会出问题
			col = getInt();
			// 输入,并处理,连续和的小技巧
			for (int r = 1; r <= row; r++) {
				for (int c = 1; c <= col; c++) {
					arr[r][c] = getInt();
					arr[r][c] += arr[r - 1][c];
				}
			}
			// 计算
			// 枚举子矩阵
			max = arr[1][1];
			for (int r = 1; r <= row; r++) {
				for (int _r = r; _r <= row; _r++) {
					int sum = 0;// 每一列的和
					for (int c = 1; c <= col; c++) {
						if (sum < 0) {
							sum = arr[_r][c] - arr[r - 1][c];
						} else {
							sum += arr[_r][c] - arr[r - 1][c];
							max = Math.max(max, sum);
						}
					}
				}
			}
			System.out.println(max);
		}
		bis.close();
	}

	static int getInt() throws Exception {
		int i, temp = 0, mark = 1;
		while ((i = bis.read()) < 45)
			;
		if (i == 45) {
			mark = -1;
			i = bis.read();
		}
		while (i > 47) {
			temp = temp * 10 + i - 48;
			i = bis.read();
		}
		return temp * mark;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值