zoukankan      html  css  js  c++  java
  • HDU 2084 数塔 (dp)

    题目链接

    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
    

    分析:

    数塔的题应该从下往上找,这样找到最后的话就只有一个最大值,而且这样还有利于输出路径。

    代码:

    #include<iostream>
    #include<stdio.h>
    #include<string.h>
    #include<algorithm>
    using namespace std;
    int main()
    {
        int N;
        scanf("%d",&N);
        while(N--)
        {
            int n,a[100][100]= {0},b[100][100]= {0},i,j;
            scanf("%d",&n);
            for(i=0; i<n; i++)
                for(j=0; j<=i; j++)
                {
                    scanf("%d",&a[i][j]);
                    b[i][j]=a[i][j];
                }
            for(i=n-2; i>=0; i--)
                for(j=0; j<=i; j++)
                {
                    if(b[i+1][j]>b[i+1][j+1])
                        b[i][j]+=b[i+1][j];
                    else
                        b[i][j]+=b[i+1][j+1];
    
                }
            int max1=b[0][0],a1,b1;
            printf("%d
    ",max1);
            /*路径的输出
            for(i=0; i<n; i++)
            {
                for(j=0; j<=i; j++)
                {
                    if(a[i][j]+b[i+1][j]==max1)
                    {
                        a1=i;
                        b1=j;
                        max1=b[i+1][j];
                        break;
                    }
                    else if(a[i][j]+b[i+1][j+1]==max1)
                    {
                        a1=i;
                        b1=j;
                        max1=b[i+1][j+1];
                        break;
                    }
                }
                if(a1==0&&b1==0)
                    printf("(0,0)");
                else
                    printf("-->(%d,%d)",a1,b1);
            }
            printf("
    ");
            */
        }
        return 0;
    }
  • 相关阅读:
    mysql的length与char_length的区别
    case when 多个条件 以及case when 权重排序
    ogitor下载地址
    简单单例模式
    求切线和次法线
    Alpha混合物体的深度排序
    C++对齐问题
    Computing Tangent Space Basis Vectors for an Arbitrary Mesh
    .NET三层架构简析
    DaGridView导出Excel
  • 原文地址:https://www.cnblogs.com/cmmdc/p/6764751.html
Copyright © 2011-2022 走看看