HDU 2084 數塔 dp
阿新 • • 發佈:2019-02-18
數塔
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 43433 Accepted Submission(s): 25694
Problem Description 在講述DP演算法的時候,一個經典的例子就是數塔問題,它是這樣描述的:
有如下所示的數塔,要求從頂層走到底層,若每一步只能走到相鄰的結點,則經過的結點的數字之和最大是多少?
已經告訴你了,這是個DP的題目,你能AC嗎?
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
Source
Recommend lcy | We have carefully selected several similar problems for you:
分析:從上往下推,好難的,一次次新增,所以就準備從下往上推,dp弄一位陣列就可以,方程dp[j] = max( dp[j+1] , dp[ j ] ) + a[ i ][ j ];
ac程式碼:
#include <stdio.h> #include <string.h> #include <math.h> #include <algorithm> using namespace std; int main(){ int t,n; int a[105][105]; int dp[105]; scanf("%d",&t); while(t--){ scanf("%d",&n); memset(a,0,sizeof(a)); for(int i=0;i<n;i++){ for(int j=0;j<=i;j++){ scanf("%d",&a[i][j]); } } memset(dp,0,sizeof(dp)); for(int i=n-1;i>=0;i--){ for(int j=0;j<=i;j++) dp[j]=max(dp[j+1],dp[j])+a[i][j]; } printf("%d\n",dp[0]); } return 0; }