zoukankan      html  css  js  c++  java
  • 数字三角形求解

    题目:

    如图所示,
                    3
                2        3
            4    3    4    4

    7个数字构成三层的数字三角形,从属关系为树形关系。要求按照从属关系,在每一层选择一个数,使最后的和最大。

    分析:

    如果从下往下选择的话,越往下选择越多,问题就越复杂。考虑从下往上选择,采用动态规划法,从局部开始考虑。局部最大,则构成整体最大。我是用C++写的。

    代码:

     1 #include <iostream>
     2 using namespace std;
     3 int main()
     4 {
     5     int triangle[100][100];
     6     int i;
     7     int j;
     8     int n;
     9     cout<<"请输入三角形的层数:";
    10     cin>>n;
    11     while(n!= 0)
    12     {
    13         cout<<"请依次输入每层三角形的值:"<<endl;
    14         for(i=1;i<=n;i++)
    15         {
    16             for(j=1;j<=i;j++)
    17             {
    18                 cin>>triangle[i][j];
    19             }
    20         }
    21 
    22         for(i=n-1;i>0;i--)
    23         {
    24             for(j=i;j>0;j--)
    25             {
    26                 triangle[i][j]+=triangle[i+1][j+1]>triangle[i+1][j]?triangle[i+1][j+1]:triangle[i+1][j];
    27             }
    28         }
    29         cout<<"该数字三角形的各层和的最大值为:"<<triangle[1][1]<<endl;
    30         break;
    31     }
    32     return 0;
    33 }
    View Code
  • 相关阅读:
    bzoj 3747: [POI2015]Kinoman
    bzoj 3123: [Sdoi2013]森林
    bzoj 1901: Zju2112 Dynamic Rankings
    poj 1741 Tree
    bzoj 2152: 聪聪可可
    bzoj 2599: [IOI2011]Race
    bzoj 3697: 采药人的路径
    bzoj 2728: [HNOI2012]与非
    bzoj 2115: [Wc2011] Xor
    bzoj 3143: [Hnoi2013]游走
  • 原文地址:https://www.cnblogs.com/leanfish/p/4414761.html
Copyright © 2011-2022 走看看