在讲述DP算法的时候,一个经典的例子就是数塔问题,它是这样描述的:
有如下所示的数塔,要求从顶层走到底层,若每一步只能走到相邻的结点,则经过的结点的数字之和最大是多少?
已经告诉你了,这是个DP的题目,你能AC吗?Input输入数据首先包括一个整数C,表示测试实例的个数,每个测试实例的第一行是一个整数N(1 <= N <= 100),表示数塔的高度,接下来用N行数字表示数塔,其中第i行有个i个整数,且所有的整数均在区间[0,99]内。Output对于每个测试实例,输出可能得到的最大和,每个实例的输出占一行。Sample Input1 5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5Sample Output30
数字三角形问题

1 #include<iostream> 2 #include<cstdio> 3 #include<algorithm> 4 #include<vector> 5 #include<queue> 6 #include<cmath> 7 #include<cstring> 8 using namespace std; 9 const int maxn=1e6+5; 10 const int INF=1e9+7; 11 int c,n,a[105][105],f[105][105]; 12 template <class t>void red(t &x) 13 { 14 x=0; 15 int w=1; 16 char ch=getchar(); 17 while(ch<'0'||ch>'9') 18 { 19 if(ch=='-') 20 w=-1; 21 ch=getchar(); 22 } 23 while(ch>='0'&&ch<='9') 24 { 25 x=(x<<3)+(x<<1)+ch-'0'; 26 ch=getchar(); 27 } 28 x*=w; 29 } 30 void input() 31 { 32 freopen("input.txt","r",stdin); 33 } 34 int main() 35 { 36 //input(); 37 red(c); 38 while(c--) 39 { 40 red(n); 41 memset(f,0,sizeof(f)); 42 for(int i=1;i<=n;++i) 43 for(int j=1;j<=i;++j) 44 red(a[i][j]); 45 for(int i=1;i<=n;++i) 46 f[n][i]=a[n][i]; 47 for(int i=n-1;i>=1;--i) 48 for(int j=1;j<=i;++j) 49 f[i][j]=max(f[i+1][j],f[i+1][j+1])+a[i][j]; 50 printf("%d ",f[1][1]); 51 } 52 return 0; 53 }