$Poj1050\ To\ the\ Max$

Poj

 

$Description$

求最大子矩阵.$1<=N<=100$

 

$Sol$

这个数据范围暴力就可以过了$qwq$

但还是要讲一下优化:预处理前缀和$sum[i][j]$表示的是$\sum_{k=1}^{i}a[k][j]$.然后就只要枚举矩阵的上下两边,于是求最大子矩阵转化成看求最大子段和.

注意矩阵里的元素可以为负!

 

$Code$

#include<iostream>
#include<cstdio>
#define il inline
#define Rg register
#define go(i,a,b) for(Rg int i=a;i<=b;++i)
#define yes(i,a,b) for(Rg int i=a;i>=b;--i)
#define mem(a,b) memset(a,b,sizeof(a))
#define ll long long
#define db double
using namespace std;
il int read()
{
    Rg int x=0,y=1;char c=getchar();
    while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=(x<<1)+(x<<3)+c-'0';c=getchar();}
    return x*y;
}
int n,as,a[110][110];
int main()
{
    n=read();
    go(i,1,n)go(j,1,n)a[i][j]=a[i][j-1]+a[i-1][j]-a[i-1][j-1]+read();
    go(x1,1,n)go(y1,1,n)
        go(x2,x1,n)go(y2,y1,n)
        as=max(as,a[x2][y2]-a[x1-1][y2]-a[x2][y1-1]+a[x1-1][y1-1]);
    printf("%d\n",as);
    return 0;
}
View 暴力 Code
#include<iostream>
#include<cstdio>
#define il inline
#define Rg register
#define go(i,a,b) for(Rg int i=a;i<=b;++i)
#define yes(i,a,b) for(Rg int i=a;i>=b;--i)
#define mem(a,b) memset(a,b,sizeof(a))
#define ll long long
#define db double
#define inf 2147483647
using namespace std;
il int read()
{
    Rg int x=0,y=1;char c=getchar();
    while(c<'0'||c>'9'){if(c=='-')y=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=(x<<1)+(x<<3)+c-'0';c=getchar();}
    return x*y;
}
int n,as=-inf,a[110][110];
int main()
{
    n=read();
    go(i,1,n)go(j,1,n)a[i][j]=a[i-1][j]+read();
    go(i,1,n)go(j,i,n)
    {
        Rg int nw=0;
        go(k,1,n)
        {
            Rg int qvq=a[j][k]-a[i-1][k];
            if(nw>=0)nw+=qvq;
            else nw=qvq;
            as=max(as,nw);
        }
    }
    printf("%d\n",as);
    return 0;
}
View 优化 Code

 

 

posted @ 2019-08-20 10:12  DTTTTTTT  阅读(123)  评论(0编辑  收藏  举报