openjudge1768 最大子矩阵[二维前缀和or递推|DP]

总时间限制: 
1000ms
 
内存限制: 
65536kB
描述
已知矩阵的大小定义为矩阵中所有元素的和。给定一个矩阵,你的任务是找到最大的非空(大小至少是1 * 1)子矩阵。

比如,如下4 * 4的矩阵

0 -2 -7 0
9 2 -6 2
-4 1 -4 1
-1 8 0 -2

的最大子矩阵是

9 2
-4 1
-1 8

这个子矩阵的大小是15。
输入
输入是一个N * N的矩阵。输入的第一行给出N (0 < N <= 100)。再后面的若干行中,依次(首先从左到右给出第一行的N个整数,再从左到右给出第二行的N个整数……)给出矩阵中的N2个整数,整数之间由空白字符分隔(空格或者空行)。已知矩阵中整数的范围都在[-127, 127]。
输出
输出最大子矩阵的大小。
样例输入
4
0 -2 -7 0 9 2 -6 2
-4 1 -4  1 -1

8  0 -2
样例输出
15
来源
翻译自 Greater New York 2001 的试题
----------------------------------
降维后用1维的DP计算最大值
枚举y1和y2,用二维前缀和或者对枚举边递推把x处y1和y2之间的一列压成一个格
//二维前缀和
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int N=105;
int n,a[N][N],s[N][N],ans=-1e5,f[N];
void init(){
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++)
            s[i][j]=s[i][j-1]+s[i-1][j]-s[i-1][j-1]+a[i][j];
}
inline int get(int x,int y1,int y2){
    return s[x][y2]-s[x-1][y2]-s[x][y1]+s[x-1][y1];
}
int main(int argc, const char * argv[]) {
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++) scanf("%d",&a[i][j]);
    init();
    for(int y2=1;y2<=n;y2++)
        for(int y1=0;y1<y2;y1++)
            for(int x=1;x<=n;x++){
                f[x]=max(0,f[x-1])+get(x,y1,y2);
                ans=max(ans,f[x]);
            }
    cout<<ans;
    return 0;
}
//c[x]递推,当前压缩的值
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int N=105;
int n,a[N][N],c[N],ans=-1e5,f[N];
int main(int argc, const char * argv[]) {
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        for(int j=1;j<=n;j++) scanf("%d",&a[i][j]);
    for(int y1=0;y1<n;y1++){
        memset(c,0,sizeof(c));
        for(int y2=y1+1;y2<=n;y2++)
            for(int x=1;x<=n;x++){
                c[x]+=a[x][y2];
                f[x]=max(0,f[x-1])+c[x];
                ans=max(ans,f[x]);
            }
    }
    cout<<ans;
    return 0;
}

 

posted @ 2016-08-26 22:27  Candy?  阅读(647)  评论(0编辑  收藏  举报