A Different Task
\epsfbox{p10795a.eps}
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.
\epsfbox{p10795b.eps}
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
题意:给你一个汉诺塔的初始态和一个目标态,求最少几步能够从初始态到目标态(移动的过程中还是要保持小的在上面等汉诺塔规则);
思路:对于每一对状态都一个参考态。考虑到最大的盘子如果两个状态都一样那么就不用操作(如果操作就不是最优解),那么我们需要找到两个态不相等的盘子的最大值k(序号)。对于k号盘子,我们需要从(比如)1柱子移动到(比如)2柱子上去,那么k-1号盘子只能放在3号柱子上,那么在3号柱子上就是从小到大依次排放(1, 2…K-1)。那么我们只需要找出来从初始态和目标态到此状态的最少步数之和,然后加1(移动k)。(参考入门经典)
代码:
#include <cstdio>
const int maxn = 70;
long long f(int* p, int k, int final){//final就是p[k]要移动到的柱子的号
if(k == 0) return 0;
else if(p[k] == final) return f(p, k-1, final);//如果p[k]在final上,那么就需要移动移动k-1号到final
else return f(p, k-1, 6-p[k]-final)+(1LL << (k-1));//因为p[k]不等于final, 那么如果要移动前K-1到第三个柱子上中转,然后再将P[K]移动到final柱子上,然后再将k-1个盘子重新移动回来,最后一个步骤是将k-1个盘子从一个柱子上移动到另外一个柱子上,由汉诺塔规律需要移动1<<(k-1)。
}
int st[maxn], en[maxn];
int main(){
int n, v = 0;
while(scanf("%d", &n), n){
for(int i = 1; i <= n; ++ i) scanf("%d", st+i);
for(int i = 1; i <= n; ++ i) scanf("%d", en+i);
int k = n;
while(k>0&&st[k] == en[k]) -- k;
long long ans = 0;
if(k > 0){ //k就是不相等的最大序号
int final = 6-st[k]-en[k];
ans += f(st, k-1, final)+f(en, k-1, final)+1;//移动1~k号。
}
printf("Case %d: %lld\n", ++v, ans);
}
return 0;
}