encu 1065 糖果盒(最大子矩阵DP)

王知昆的论文的第二种方法。。。。。

开始没有更新height,WA了半天。。。。。

AC代码如下:

#include 
#include 
#include 
#include 
using namespace std;

int num[1100][1100], sum[1100][1100];
int _left[1100][1100], _right[1100][1100], height[1100][1100];
int N, M, ans;

int calc_sum( int x, int y, int l, int r, int h ){
    int ret;
    ret = sum[x][r-1] + sum[x-h][l] - sum[x-h][r-1] - sum[x][l];
    return ret;
}

int main(){

    memset( num, 0, sizeof( num ) );
    memset( sum, 0, sizeof( sum ) );

    while( scanf( "%d%d", &N, &M ) != EOF ){

        ans = 0;

        for( int i = 1; i <= N; i++ ){
            for( int j = 1; j <= M; j++ ){
                scanf( "%d", &num[i][j] );
                sum[i][j] = sum[i-1][j] + sum[i][j-1] - sum[i-1][j-1] + num[i][j];
            }
        }

        memset( height, 0, sizeof( height ) );
        for( int i = 1; i <= N; i++ ){

            _left[i][0] = 0;
            for( int j = 1; j <= M; j++ ){
                if( num[i][j] == 0 )    _left[i][j] = j;
                else    _left[i][j] = _left[i][j-1];
            }

            _right[i][M+1] = M + 1;
            for( int j = M; j >= 1; j-- ){
                if( num[i][j] == 0 )    _right[i][j] = j;
                else    _right[i][j] = _right[i][j+1];
            }

            for( int j = 1; j <= M; j++ ){
                if( num[i][j] == 0 ){
                    height[i][j] = 0;
                    continue;
                }else if( num[i-1][j] == 0 ){
                    height[i][j] = 1;
                    ans = max( ans, calc_sum( i, j, _left[i][j], _right[i][j], height[i][j] ) );
                }else{
                    height[i][j] = height[i-1][j] + 1;
                    _left[i][j] = max( _left[i][j], _left[i-1][j] );//这里要注意。。。不能漏了
                    _right[i][j] = min( _right[i][j], _right[i-1][j] );//这里要注意。。。。。不能漏了
                    ans = max( ans, calc_sum( i, j, _left[i][j], _right[i][j], height[i][j] ) );
                }
            }
        }

        printf( "%d\n", ans );
    }
    return 0;
}


你可能感兴趣的:(动态规划)