hdu 1081 利用前缀和求最大字段和

和1003类似,就是求最大字段和,只不过这个要先出理每一行的前缀和,然后枚举每一段的高度

1003的链接

代码如下:

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
#define MAX 107
#define INF 0xffffffff

using namespace std;

int sum[MAX][MAX];
int n,a;

int main ( )
{
    while  (~scanf  ( "%d" , &n ) )
    {
        memset ( sum , 0 , sizeof ( sum ) );
        for ( int i = 1 ; i <= n ; i ++ )
        {
            for ( int j = 1 ; j <= n ; j++ )
            {
                scanf ( "%d" , &a );
                sum[i][j] = sum[i][j-1] + a;
            }
        }
        int maxn = -INF;       
        for ( int i = 1 ; i <= n ; i++ )
            for ( int j =i ; j <=n ; j++ )
            {
                int cur = 0;
                for ( int k = 1 ; k <= n ; k++ )
                {
                     if ( cur < 0 ) cur = 0;
                     cur += sum[k][j] - sum[k][i-1];
                     maxn = max ( cur , maxn ); 
                }
            }
        printf ( "%d\n" , maxn );
    }
}


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