General question:
Enter an n-layer triangle. the I-th layer has the number of I. Find the route with the largest sum of weights from layer 1st to layer n.
Rule: a certain number of I layers can only be connected to one of the two numbers adjacent to the position in I + 1.
F [I] [j]: indicates the maximum weight sum between column j of row I and the last row;
State equation:
F [I] [j] = w [I] [j] + max (f [I + 1] [j], f [I + 1] [j + 1]);
/ Time 157ms; Memory 1236K // Time 157ms; Memory 1236K[cpp] view plaincopyprint?#include<iostream> using namespace std; int max(int a,int b) { return a>b?a:b; } int main() { int i,j,n,w[355][355],f[355][355]; cin>>n; for(i=0;i<n;i++) { for(j=0;j<=i;j++) cin>>w[i][j]; } for(i=0;i<n;i++) f[n-1][i]=w[n-1][i]; for(i=n-2;i>=0;i--) { for(j=0;j<=i;j++) f[i][j]=w[i][j]+max(f[i+1][j],f[i+1][j+1]); } cout<<f[0][0]<<endl; return 0; } #include<iostream>using namespace std;int max(int a,int b){ return a>b?a:b;}int main(){ int i,j,n,w[355][355],f[355][355]; cin>>n; for(i=0;i<n;i++) { for(j=0;j<=i;j++) cin>>w[i][j]; } for(i=0;i<n;i++) f[n-1][i]=w[n-1][i]; for(i=n-2;i>=0;i--) { for(j=0;j<=i;j++) f[i][j]=w[i][j]+max(f[i+1][j],f[i+1][j+1]); } cout<<f[0][0]<<endl; return 0;}