您的位置:首页 > 其它

UVA 10795 <递归>

2014-12-28 19:40 134 查看
首先必然先考虑大盘子,因为大盘子一旦到达他的目标位置之后必然是不需要再动的,这之后就都可以忽略他的存在啦。最大的没有到达目标位置的盘子的编号是k那么现在的认为是不是把k盘子放到他的指定位置b[k]上呢。那么在把这个盘子放到目标位置之前的那一刻,其他盘子的位置是什么样子呢,这时候因为可以移动k盘子啦,所以有k的柱子k盘子上面必然没盘子,在他下面的盘子必然是比他小的盘子,在他的目标位置上必然也没有比他小的盘子,也就是说比他小的盘子都在除了他现在在的那个柱子和目标柱子之外的盘子。设这个状态是参考状态。因为盘子的移动是可逆的那么如果能从目标状态的移动到参考状态,那么参考状态必然也能用相同的步骤移动到目标状态,如果把开始状态和目标状态都移动到参考状态的话,再把k盘子移动到目标柱子上的时候是不是说明能从开始状态移动到目标状态。而该方法的步数就是开始状态->参考状态-
->目标状态

设一个函数f(p,i,fin);这个函数的意思是把盘子1-----i全部移动 到fin的柱子上所花费的步数,如果现在第i个盘子已经在fin的位置上那么现在f(p,i,fin) = f(p,i-1,fin);啦但是如果第i个盘子不在目标位置那么就需要把盘子1----i-1移动到不是6-p[i]-fin的柱子上,也就是f(p,i-1,6-p[i]-fin)然后把i盘子放到fin的位置上然后把在6-p[i]-fin柱子上的上的i-1个盘子移动刀fin柱子上,根据汉诺塔的经典理论,这是要2^(i-1)-1步的所有就有如上代码

UVA - 10795

A Different Task

Time Limit: 3000MSMemory Limit: Unknown64bit IO Format: %lld & %llu
Submit Status

Description







A Different Task



The (Three peg) Tower of Hanoi problem is a popular one in computer science. Briefly the problem is to transfer all the disks from peg-A to peg-C using peg-B as
intermediate one in such a way that at no stage a larger disk is above a smaller disk. Normally, we want the minimum number of moves required for this task. The problem is used as an ideal example for learning recursion. It is so well studied that one can
find the sequence of moves for smaller number of disks such as 3 or 4. A trivial computer program can find the case of large number of disks also.

Here we have made your task little bit difficult by making the problem more flexible. Here the disks can be in any peg initially.



If more than one disk is in a certain peg, then they will be in a valid arrangement (larger disk will not be on smaller ones). We will give you two such arrangements of disks. You will have to find out the minimum number of moves, which will transform the first
arrangement into the second one. Of course you always have to maintain the constraint that smaller disks must be upon the larger ones.

Input

The input file contains at most 100 test cases. Each test case starts with a positive integer N ( 1

N

60),
which means the number of disks. You will be given the arrangements in next two lines. Each arrangement will be represented by N integers, which are 1, 2 or 3.
If the i-th ( 1

i

N)
integer is 1, you should consider that i-th disk is on Peg-A. Input is terminated by N =
0. This case should not be processed.

Output

Output of each test case should consist of a line starting with `Case #: ' where # is the test case number.
It should be followed by the minimum number of moves as specified in the problem statement.

Sample
Input

3
1 1 1
2 2 2
3
1 2 3
3 2 1
4
1 1 1 1
1 1 1 1
0


Sample
Output

Case 1: 7
Case 2: 3
Case 3: 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: