标签:
1 5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
30
解析:dp,用二维数组d[i][j]存数塔,maxsum[i][j]代表从i,j位置出发到终点所能走过的路径总和的最大值,由于只能向下、向右走,所以状态转移方程就是maxsum[i][j] = max( getsum(i+1, j), getsum(i+1, j+1) ) + d[i][j];还有一点就是利用记忆化搜索,当d[i][j]已经计算过了,就不用再计算了。
AC代码:
#include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <vector> #include <queue> #include <set> #include <map> #include <string> #include <cmath> #include <cstdlib> #include <ctime> #include <stack> using namespace std; #define INF 0x7fffffff #define LL long long #define MID(a, b) a+(b-a)/2 const int maxn = 100 + 10; int maxsum[maxn][maxn], d[maxn][maxn]; int n; int getsum(int i, int j){ if(maxsum[i][j] != -1) return maxsum[i][j]; //记忆化,已经计算过了,直接返回即可 if(i == n) maxsum[i][j] = d[i][j]; //递归出口 else maxsum[i][j] = max( getsum(i+1, j), getsum(i+1, j+1) ) + d[i][j]; //转移方程 return maxsum[i][j]; } int main(){ #ifdef sxk freopen("in.txt", "r", stdin); #endif // sxk int t; scanf("%d", &t); while(t--){ scanf("%d", &n); memset(d, 0, sizeof(d)); memset(maxsum, -1, sizeof(maxsum)); for(int i=1; i<=n; i++) for(int j=1; j<=i; j++) scanf("%d", &d[i][j]); printf("%d\n", getsum(1, 1)); } return 0; }
标签:
原文地址:http://blog.csdn.net/u013446688/article/details/43311987