POJ3601_“TowerofHanoi”汉诺塔问题变型探讨.doc

POJ3601_“TowerofHanoi”汉诺塔问题变型探讨.doc

  1. 1、本文档共3页,可阅读全部内容。
  2. 2、原创力文档(book118)网站文档一经付费(服务费),不意味着购买了该文档的版权,仅供个人/单位学习、研究之用,不得用于商业用途,未经授权,严禁复制、发行、汇编、翻译或者网络传播等,侵权必究。
  3. 3、本站所有内容均由合作方或网友上传,本站不对文档的完整性、权威性及其观点立场正确性做任何保证或承诺!文档内容仅供研究参考,付费前请自行鉴别。如您付费,意味着您自己接受本站规则且自行承担风险,本站不退款、不进行额外附加服务;查看《如何避免下载的几个坑》。如果您已付费下载过本站文档,您可以点击 这里二次下载
  4. 4、如文档侵犯商业秘密、侵犯著作权、侵犯人身权等,请点击“版权申诉”(推荐),也可以打举报电话:400-050-0827(电话支持时间:9:00-18:30)。
查看更多
POJ3601_“TowerofHanoi”汉诺塔问题变型探讨

汉诺塔变形 POJ 3601 Tower of Hanoi 递推 2008-07-31 12:16 Tower of Hanoi Time Limit:?1000MSMemory Limit:?131072KTotal Submissions:?423Accepted:?92Description The Tower of Hanoi is a puzzle consisting of three pegs and a number of disks of different sizes which can slide onto any peg. The puzzle starts with the disks neatly stacked in order of size on one peg, the smallest at the top, thus making a conical shape. The objective of the puzzle is to move the entire stack to another peg, obeying the following rules: Only one disk may be moved at a time. Each move consists of taking the upper disk from one of the pegs and sliding it onto another peg, on top of the other disks that may already be present on that peg. No disk may be placed on top of a smaller disk. For?n?disks, it is a well-known result that the optimal solution takes 2n?? 1 moves. To complicate the puzzle a little, we allow multiple disks to be of the same size. Moreover, equisized disks are mutually distinguishable. Their ordering at the beginning should be preserved at the end, though it may be disturbed during the process of solving the puzzle. Given the number of disks of each size, compute the number of moves that the optimal solution takes. Input The input contains multiple test cases. Each test case consists of two lines. The first line contains two integers?n?and?m?(1 ≤?n?≤ 100, 1 ≤?m?≤ 106). The second lines contains?n?integers?a1,?a2, …,?an?(1 ≤?a1,?a2, …,?an?≤ 105). For each 1 ≤?i?≤?n, there are?ai?disks of size?i. The input ends where EOF is met. Output For each test case, print the answer modulo?m?on a separate line. Sample Input 1 1000 2 5 1000 1 1 1 1 1 5 1000 2 2 2 2 2 5 1000 1 2 1 2 1 Sample Output 3 31 123 41  题意: 古老的汉诺塔问题,也是有由3个杆,但是叠的圆盘可能会有相同大小的,对于相同大小的圆盘,在最后移动完毕之后也必须保证按照原来的顺序排放,问移动的最少步数 思路: 考虑最原始的汉诺塔,也就是每种圆盘只有一个,那么用dp[i]表示对于i层得最少移动步数,有dp[i]=dp[i-1]*2+1,移动放法是移动前i-1个,再移动第i个,再移动前i-1个 那么对于这道题,其实唯一不同的地方就是,对于一样大小的圆盘,如果直接移动到目的地,那么他们的标号就会变反(比如123-321),对??两种以上的圆盘,那么按照之前的移动方式,前i-1堆会是顺序排放的,最后一堆会

文档评论(0)

jgx3536 + 关注
实名认证
内容提供者

该用户很懒,什么也没介绍

版权声明书
用户编号:6111134150000003

1亿VIP精品文档

相关文档