Chinaunix首页 | 论坛 | 博客
  • 博客访问: 65405
  • 博文数量: 115
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 10
  • 用 户 组: 普通用户
  • 注册时间: 2014-03-08 19:09
文章分类
文章存档

2015年(115)

我的朋友

分类: Python/Ruby

2015-08-06 16:51:51

原文地址:数字三角形 作者:runningdark



 
数字三角形 

问题描述 


3 8 

8 1 0 

2 7 4 4 

4 5 2 6 5 


上图给出了一个数字三角形。从三角形的顶部到底部有很多条不同的路径。对于每条路
径,把路径上面的数加起来可以得到一个和,和最大的路径称为最佳路径。你的任务就是求
出最佳路径上的数字之和。


注意:路径上的每一步只能从一个数走到下一层上和它最近的左边的数或者右边的数。


  1. my @result;
  2. my @data =(
  3.     [1],
  4.     [2,3],
  5.     [4,5,6],
  6.     [7,8,9,10],
  7.     [14,3,6,8,6]
  8. );

  9. #the path value to the first element is 1
  10. $result[0][0] = $data[0][0];

  11. sub MaxSingleStep{

  12.     #now get the path with max value to $data[$level][$tarI]
  13.     my $tarI = shift;
  14.     my $level = shift;


  15.     #get the possible element which can reach [$level][$tarI]
  16.     my $si = $tarI - 1 ;
  17.     my $ei = $tarI +1;
  18.     if($si < 0){
  19.         $si = 0;
  20.     }


  21.     #select the element with max path value
  22.     my $pathv = 0;
  23.     for($si..$ei){
  24.         if($pathv < $result[$level-1][$_] and defined($result[$level-1][$_])){
  25.             $pathv = $result[$level-1][$_];
  26.         }
  27.     }

  28.     #the path value is the sum of selected element path value the current element
  29.     $result[$level][$tarI] = $pathv + $data[$level][$tarI];
  30. }




  31. #go through all element by level
  32. for my $level (1..4){
  33.     #go through element in every level
  34.     for my $index (0..$level){
  35.         MaxSingleStep($index,$level);
  36.     }
  37. }

  38. #output
  39. my $max = 0;
  40. for(@result[@data-1]){
  41.     for(@{$_}){
  42.         $max = $_ if($max<$_);
  43.     }
  44. }
  45. print $max;




 





阅读(1746) | 评论(0) | 转发(0) |
0

上一篇:叠放箱子

下一篇:采蘑菇(fungus.pas)

给主人留下些什么吧!~~