资源限制
时间限制:1.0s 内存限制:256.0MB
问题描述
给定一个n*m的矩阵A,求A中的一个非空子矩阵,使这个子矩阵中的元素和最大。
其中,A的子矩阵指在A中行和列均连续的一块。
输入格式
输入的第一行包含两个整数n, m,分别表示矩阵A的行数和列数。
接下来n行,每行m个整数,表示矩阵A。
输出格式
输出一行,包含一个整数,表示A中最大的子矩阵中的元素和。
样例输入
3 3
-1 -4 3
3 4 -1
-5 -2 8
样例输出
10
样例说明
取最后一列,和为10。
数据规模和约定
对于50%的数据,1<=n, m<=50;
对于100%的数据,1<=n, m<=500,A中每个元素的绝对值不超过5000。
————————————————————————————————————————————————
方法1:神仙才能想到的。参考原文
这方法太难想了吧。。
import java.util.Scanner;
public class Main {
static int[][] map = new int[505][505];
static int[][] cmap = new int[505][505];
static int[] rmap = new int[505];
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n, m, i, j, k, ans = -5000;
n = sc.nextInt();
m = sc.nextInt();
for (i = 1; i <= n; i++) {
for (j = 1; j <= m; j++) {
map[i][j] = sc.nextInt();
cmap[i][j] = cmap[i - 1][j] + map[i][j];
}
}
for (i = 0; i <= n; i++) {
for (j = i + 1; j <= n; j++) {
for (k = 1; k <= m; k++) {
rmap[k] = cmap[j][k] - cmap[i][k];
}
for (k = 1; k <= m; k++) {
if (rmap[k - 1] > 0) rmap[k] += rmap[k - 1];
if (rmap[k] > ans) ans = rmap[k];
}
}
}
System.out.println(ans);
}
}
方法2:凡人能想到的(只能得50分)
用二维前缀和数组,再枚举所有的坐标对:左上角点(i, j) 和 右下角点(i2, j2)
import java.util.Scanner;
public class Main {
static int n, m;
static int[][] g;
static int[][] S;
static Pair[] arr;//把每个点的坐标存下来
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
m = sc.nextInt();
arr = new Pair[n * m + 10];
int index = 1;
g = new int[n + 1][m + 1];
S = new int[n + 1][m + 1];
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
arr[index++] = new Pair(i, j);
g[i][j] = sc.nextInt();
S[i][j] = S[i - 1][j] + S[i][j - 1] - S[i - 1][j - 1] + g[i][j];
}
}
int res = Integer.MIN_VALUE;
index = 1;
while (index <= n * m) {
for (int i = 1; i <= n * m; i++) {
Pair s = arr[index];//index是左上角点的下标
Pair t = arr[i];//i是右下角点的下标
if (t.x < s.x || t.y < s.y) continue;
res = Math.max(res, query(s.x, s.y, t.x, t.y));
}
index++;
}
System.out.println(res);
}
private static int query(int i, int j, int i2, int j2) {//返回子矩阵的和
return S[i2][j2] - S[i - 1][j2] - S[i2][j - 1] + S[i - 1][j - 1];//这里容易写错
}
}
class Pair {
int x;
int y;
public Pair(int x, int y) {
this.x = x;
this.y = y;
}
}