题意:
求最大连续子矩阵和
思路:
uva507 最大连续子序列的变形:http://blog.csdn.net/conatic/article/details/50839119
枚举第i行到第j行的和,再从i到j行的各列和依次累加,存入数组b,这样就转为一维的求数组b的最大连续子序列和的问题了。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 105;
int a[N][N], b[N];
int n;
int max_sum(int arr[]) {
int sum = arr[0], maxn = -1;
for (int i = 1; i<n; i++) {
if (sum > 0)
sum += arr[i];
else
sum = arr[i];
if (sum>maxn)
maxn = sum;
}
return maxn;
}
int main() {
while (~scanf("%d", &n)) {
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
scanf("%d", &a[i][j]);
int sum, maxn = -0x3f3f3f3f;
for (int i = 0; i < n; i++) {
for (int k = 0; k < n; k++)
b[k] = 0;
for (int j = i; j < n; j++){
//第i行到第j列
for (int k = 0; k < n; k++)
b[k] += a[j][k];
sum = max_sum(b);
maxn = max(maxn, sum);
}
}
printf("%d\n", maxn);
}
}