DP入門

A - DP入門
Time Limit:1000MS    Memory Limit:32768KB    64bit IO Format:%I64d & %I64u

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
#include<stdio.h>
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
    int n;
    int a;

    int b[105][105],c[105][105];
    while(scanf("%d",&n)!=EOF)
    {
         while(n--)
    {
        int maxn=0;
        memset(b,0,sizeof(b));
        memset(c,0,sizeof(c));
        scanf("%d",&a);
        for(int i=1;i<=a;i++)
            for(int j=1;j<=i;j++)
            scanf("%d",&b[i][j]);
        c[1][1]=b[1][1];
        for(int k=2;k<=a;k++)
           for(int t=1;t<=k;t++)
           {
               c[k][t]=b[k][t]+max(c[k-1][t-1],c[k-1][t]);
           }

           for(int p=1;p<=a;p++)
           {
                maxn=max(maxn,c[a][p]);

           }

        printf("%d\n",maxn);
    }
    }

    return 0;
}

從上向下分析,從下向上求解


發佈了44 篇原創文章 · 獲贊 0 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章