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

来源:互联网 发布:怎么才可以做淘宝模特 编辑:程序博客网 时间:2024/05/23 09:43

链接: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个整数;
输出
输出矩阵的最大子矩阵的元素之和。
样例输入
14 40 -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>


0 0
原创粉丝点击