数字三角形
d (i, j) = a(i, j) + max(d(i + 1, j ), d(i + 1, j + 1) )
#include <cstdio> #include <iostream> #include <algorithm> #include <cmath> using namespace std; int n; int a[100][100]; int d[100][100]; void display(int i, int j){ if(i == n) return; cout<<a[i][j]<<endl; if(d[i][j] == d[i+1][j] + a[i][j]) display(i + 1, j); else display(i + 1, j + 1); } int dp1(int i,int j){ if(i == n) return 0; if(d[i][j]) return d[i][j]; d[i][j] = a[i][j]; d[i][j] += max(dp1(i+1,j), dp1(i+1,j+1)); return d[i][j]; } int dp2(){ for(int i = 0; i < i; i++) d[n-1][i] = a[n-1][i]; for(int i = n-2; i > -1; i--) for(int j = 0; j < i; j++) d[i][j] = max(d[i+1][j], d[i+1][j+1]); } int main(){ scanf("%d",&n); for(int i = 0; i < n; i++) for(int j = 0; j <= i; j++) scanf("%d", &a[i][j]); dp1(0,0); //dp2(); display(0,0); return 0; }