poj3176 简单dp

就是一个数塔,可以用一维数组节省空间。

状态转移方程:dp[i][j] = a[i][j] + max( dp[i+1][j], dp[i+1][j+1])

#include 
#include 
using namespace std;

#define M 355

short a[M][M];
int dp[M], n;

inline int max(short a, short b)
{
    return a > b ? a : b;
}

int DP()
{
    int i, j;

    for (i = 0; i < n; i++) dp[i] = a[n-1][i];
    for (i = n - 2; i >= 0; i--) {
        for (j = 0; j <= i; j++)
            dp[j] = a[i][j] + max(dp[j], dp[j+1]);
    }
    return dp[0];
}

int main()
{
    while (scanf ("%d", &n) != EOF) {
         for (int i = 0; i < n; i++) {
             for (int j = 0; j <= i; j++)
                scanf ("%hd", &a[i][j]);
         }
         printf ("%d\n", DP());
    }
    return 0;
}



你可能感兴趣的:(DP)