#include<iostream> #include<stdio.h> #include<algorithm> using namespace std; int max(int sum1,int sum2); int dp(int i,int j,int **,int num,int **); int main() { //freopen("acm.acm","r",stdin); int num; cin>>num; int * * a; int * * ans; a = new int *[num]; ans = new int * [num]; int i,j; for(i = 0; i < num; i ++) { a[i] = new int[num]; } for(i = 0; i < num; i ++) ans[i] =new int[num]; for(i = 0; i < num; i ++) for(j = 0; j <= i; j ++) { cin>>a[i][j]; ans[i][j] = -1; } // for(i = 0; i <num; i ++) // { // for(j = 0; j <= i; j ++) // cout<<a[i][j]<<" "; // cout<<endl; // } cout<<a[0][0] + dp(0,0,a,num,ans)<<endl; } int dp(int i,int j,int **a,int num,int **ans) { int sum1 = 0; int sum2 = 0; if(i + 1 <= num -1) { if(ans[i+1][j] != -1) sum1 = a[i+1][j]+ans[i+1][j]; else sum1 = a[i+1][j]+dp(i+1,j,a,num,ans); if(ans[i+1][j+1] != -1) sum2 = a[i+1][j+1]+ans[i+1][j+1]; else sum2 = a[i+1][j+1]+dp(i+1,j+1,a,num,ans); ans[i][j] = max(sum1,sum2); return max(sum1,sum2); } return 0; } int max(int sum1,int sum2) { //return sum1 > sum2 ? sum1 : sum2; if(sum1>sum2) return sum1; else return sum2; }
关注我的公众号,当然,如果你对Java, Scala, Python等技术经验,以及编程日记,感兴趣的话。
技术网站地址: vmfor.com