HDU 2084數塔
Problem Description 在講述DP算法的時候,一個經典的例子就是數塔問題,它是這樣描述的:
Input 輸入數據首先包括一個整數C,表示測試實例的個數,每個測試實例的第一行是一個整數N(1 <= N <= 100),表示數塔的高度,接下來用N行數字表示數塔,其中第i行有個i個整數,且所有的整數均在區間[0,99]內。
Output 對於每個測試實例,輸出可能得到的最大和,每個實例的輸出佔一行。
Sample Input
1 5 7 3 8 8 1 0 2 7 4 4 4 5 2 6 5
Sample Output
30 |
//從0 ~ n-1 行
#include<iostream>
#include<string.h>
using namespace std;
int a[105][105];//儲存數塔
int d[105][105];//從該點到底端的最大數字和
int i,j,n;
int dp(int i,int j)
{
if(d[i][j]>=0)
return d[i][j];
else
{
d[i][j]=a[i][j]+(i==n?0:max(dp(i+1,j),dp(i+1,j+1)));
return d[i][j];
}
}
int main()
{
int T;
cin>>T;
while(T--)
{
cin>>n;
memset(d,-1,sizeof(d));
for(i=0;i<n;i++)
for(j=0;j<=i;j++)
{
cin>>a[i][j];
}
cout<<dp(0,0)<<endl;
// 後期測試整個d數組
// dp(0,0);
// for(int i=0;i<n;i++)
// {
// for(int j=0;j<=i;j++)
// {
// cout<<d[i][j]<<" ";
// }
// cout<<endl;
// }
}
return 0;
}
樣例 數塔
7 | ||||
3 | 8 | |||
8 | 1 | 0 | ||
2 | 7 | 4 | 4 | |
4 | 5 | 2 | 6 | 5 |
數組d
30 | ||||
23 | 21 | |||
20 | 13 | 10 | ||
7 | 12 | 10 | 10 | |
4 | 5 | 2 | 6 | 5 |