历届试题 最大子阵
时间限制:1.0s 内存限制:256.0MB
问题描述
给定一个n*m的矩阵A,求A中的一个非空子矩阵,使这个子矩阵中的元素和最大。
其中,A的子矩阵指在A中行和列均连续的一块。
其中,A的子矩阵指在A中行和列均连续的一块。
输入格式
输入的第一行包含两个整数n, m,分别表示矩阵A的行数和列数。
接下来n行,每行m个整数,表示矩阵A。
接下来n行,每行m个整数,表示矩阵A。
输出格式
输出一行,包含一个整数,表示A中最大的子矩阵中的元素和。
样例输入
3 3
-1 -4 3
3 4 -1
-5 -2 8
-1 -4 3
3 4 -1
-5 -2 8
样例输出
10
样例说明
取最后一列,和为10。
数据规模和约定
对于50%的数据,1<=n, m<=50;
对于100%的数据,1<=n, m<=500,A中每个元素的绝对值不超过5000。
对于100%的数据,1<=n, m<=500,A中每个元素的绝对值不超过5000。
思路:看以前的题解 http://blog.youkuaiyun.com/qq_25605637/article/details/47206693
AC代码:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <cstring>
#include <climits>
#include <cmath>
#include <cctype>
const int inf = 0x7f7f7f7f;//2139062143
typedef long long ll;
using namespace std;
int map1[510][510];
int b[510];
int main()
{
int n,m;
while(scanf("%d%d",&n,&m) != EOF)
{
int max = -510;
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
scanf("%d",&map1[i][j]);
}
}
for(int i=0; i<n; i++)
{
memset(b,0,sizeof(b));
for(int j=i; j<n; j++)
{
int sum = 0;
for(int k=0; k<m; k++)
{
b[k] += map1[j][k];
sum += b[k];
if(sum > max)
{
max = sum;
}
if(sum < 0)
{
sum = 0;
}
}
}
}
printf("%d\n",max);
}
return 0;
}