最大子矩阵求和 NYOJ 104 && 372 && HDU 1081

链接:click here

给定一个由整数组成二维矩阵(r*c),现在需要找出它的一个子矩阵,使得这个子矩阵内的所有元素之和最大,并把这个子矩阵称为最大子矩阵。 
例子:
0 -2 -7 0 
9 2 -6 2 
-4 1 -4 1 
-1 8 0 -2 
其最大子矩阵为:

9 2 
-4 1 
-1 8 
其元素总和为15。 

输入
第一行输入一个整数n(0<n<=100),表示有n组测试数据;
每组测试数据:
第一行有两个的整数r,c(0<r,c<=100),r、c分别代表矩阵的行和列;
随后有r行,每行有c个整数;
输出
输出矩阵的最大子矩阵的元素之和。
样例输入
1
4 4
0 -2 -7 0 
9 2 -6 2 
-4 1 -4 1 
-1 8 0 -2 
样例输出
15

代码:

<span style="font-size:14px;">#include <math.h>
#include <queue>
#include <deque>
#include <vector>
#include <stack>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>
#include <iomanip>
#include <iostream>
#include <algorithm>

using namespace std;
#define lowbit(a) a&-a
#define Max(a,b) a>b?a:b
#define Min(a,b) a>b?b:a
#define mem(a,b) memset(a,b,sizeof(a))
int dir[4][2]= {{1,0},{-1,0},{0,1},{0,-1}};
const double eps = 1e-6;
const double Pi = acos(-1.0);
static const int inf= ~0U>>2;
static const int maxn =305;
int map[maxn][maxn],mapp[maxn];
int main()
{
    //freopen("11.txt","r",stdin);
    //freopen("22.txt","w",stdout);
    int n,m,s,k,i,j;
    cin>>n;
    while(n--)
    {
        cin>>m>>s;
        for(i=1; i<=m; i++)
            for(j=1; j<=s; j++)
            {
                cin>>map[i][j];
                map[i][j]+=map[i-1][j];
            }
        int max=map[1][1];
        for(i=0; i<=m-1; i++)
            for(j=i+1; j<=m; j++)
            {
                mem(mapp,0);
                for(k=1; k<=s; k++)
                {
                    if(mapp[k-1]>=0)
                        mapp[k]=mapp[k-1]+map[j][k]-map[i][k];
                    else
                        mapp[k]=map[j][k]-map[i][k];
                    if(max<mapp[k])
                        max=mapp[k];
                }
            }
        cout<<(max)<<endl;
    }
    return 0;
}
</span>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值