
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 ( 1N
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
关键点:(考虑最大编号的盘子)
1.如果盘子在初始局面和最终局面中位于同一柱子上,则不需要移动;
==>找到所在柱子不同编号最大的盘子
2.假设需将盘子K从1号柱子移动到3号柱子,那么K上所有盘子只能先放到2号柱子上(6-1-3=2)
3,。盘子的移动具有对称行,根据对成型,值需求出开始局面和最后总局面到参考局面的步数和;
。。。。。。。。。。
具体见《训练指南》P27:
#include <stdio.h>
#include <math.h>
#include <algorithm>
#include <string.h>
#include <stdlib.h>
using namespace std;
const int maxn = 10;
int start[70];
int end[70];
long long f(int* p,int i,int final)
{
if(i==0)
return 0;
if(p[i] == final)
return f(p,i-1,final);
else
return (f(p,i-1,6-final-p[i])+(1LL<<(i-1)));
}
int main()
{
int N;
int time = 0;
while(scanf("%d",&N)==1)
{
time++;
int i;
if(N==0)
break;
for(i = 1;i<=N;++i)
scanf("%d",&start[i]);
for(i = 1;i<=N;++i)
scanf("%d",&end[i]);
int k=N;
while(k>=1&&start[k]==end[k])
k--;
long long sum = 0;
if(k>=1)
{
int other = 6-end[k] - start[k];
sum = f(start,k-1,other)+f(end,k-1,other)+1;
}
printf("Case %d: %lld\n",time,sum);
}
return 0;
}