poj3176 Cow Bowling DP

来源:互联网 发布:苹果cms h站 编辑:程序博客网 时间:2024/06/02 11:54

The cows don't use actual bowling balls when they go bowling. They each take a number (in the range 0..99), though, and line up in a standard bowling-pin-like triangle like this: ……

题意:给你一个非负整数组成的数字三角形,第一行只有一个数,除了最下行之外每个数的左下方和右下方都各有一个数,从第一行的数开始,每次可以往左下和右下走一格,直到走到最下行,把沿途经过的数都加起来,让你求所有可能情况中得数的最大值。

题解:动态规划。状态方程:下一步是上一步左边加此步和上一步右边加此步的最大值。然后在最后一行找出最大值就可。

dp[i][j]=max(dp[i-1][j]+dp[i][j],dp[i-1][j-1]+dp[i][j]);

#include<iostream>#include<cstring>#include<cstdlib>#include<cstdio>using namespace std;#define max(a,b) (a)>(b)? a:bint main(){    int dp[505][505];    int n;    while(cin>>n)    {        memset(dp,0,sizeof(dp));        for(int i=1;i<=n;i++)            for(int j=1;j<=i;j++)        {            cin>>dp[i][j];        }        for(int i=2;i<=n;i++)            for(int j=1;j<=i;j++)        {            dp[i][j]=max(dp[i-1][j]+dp[i][j],dp[i-1][j-1]+dp[i][j]);        }        int tmp=0;        for(int k=1;k<=n;k++)        {            if(dp[n][k]>tmp)                tmp=dp[n][k];        }        cout<<tmp<<endl;    }}