题目链接: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;
}
}