The (Three peg) Tower of Hanoi problem is a popular one in computer
science. Brie y 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 nd the sequence of moves for smaller number of disks such as
3 or 4 . A trivial computer program can nd the case of large number
of disks also. Here we have made your task little bit difficult by
making the problem more exible. 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 nd
out the minimum number of moves, which will transform the rst
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 le 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 speci ed in the problem statement.
记solve(k,p)表示从开始状态到使得1..k的盘子全部在位置p需要的步数。
记solve1表示开始状态为起始状态,solve2表示开始状态为目标状态,那么找见最大的不在规定位置的k,先把1..k-1移动到第三个柱子,把k移动到规定位置,再把1..k-1移动到规定位置。答案就是solve1(k-1,6-a[k]-b[k])+solve2(k-1,6-a[k]-b[k])+1,其中a、b分别表示起始状态和目标状态。
下面以求解solve1为例,如果a[k]==p,答案就是solve1(k-1,p),否则需要先把1..k-1移到第三个柱子,把k移动到规定位置,再把1..k-1移到它上面,所以答案是solve1(k-1,6-a[k]-p)+2^(k-1)。
#include<cstdio>
#include<cstring>
int a[65],b[65],n;
#define LL long long
LL solve1(int k,int p)
{
if (!k) return 0;
if (a[k]==p) return solve1(k-1,p);
return solve1(k-1,6-a[k]-p)+(1LL<<(k-1));
}
LL solve2(int k,int p)
{
if (!k) return 0;
if (b[k]==p) return solve2(k-1,p);
return solve2(k-1,6-b[k]-p)+(1LL<<(k-1));
}
int main()
{
int i,k,K=0;
while (scanf("%d",&n)&&n)
{
for (i=1;i<=n;i++)
scanf("%d",&a[i]);
for (i=1;i<=n;i++)
scanf("%d",&b[i]);
for (k=n;k&&a[k]==b[k];k--);
printf("Case %d: ",++K);
if (k)
printf("%lld\n",solve1(k-1,6-a[k]-b[k])+solve2(k-1,6-a[k]-b[k])+1);
else
printf("0\n");
}
}