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.
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
没啥多说的,连着做了三道递归类型的题目,我的软肋也暴露出来了,我感觉考察并锻炼一个人编程水平高低与思维能力强弱的最好方法就是让他做此类题目。
直接看的Liu的思想,算法直接引用Hanoi的经典结论,减小程序工作量,利用了一些巧妙的思想——设立参考状态。
这周末决定专门给自己开个爆搜、回溯、递归专题了。把汉诺塔问题好好琢磨一下,同类的内容好好总结一下。周末贴一个总结文章的链接在这~
附代码如下:
#include<cstdio>
using namespace std;
#define ll long long int
#define MAXN (60+5)
int st[MAXN],ed[MAXN];
ll f(int *a,int k,int final){
if(k==0)return 0;
if(a[k]==final)return f(a,k-1,final);
return f(a,k-1,6-a[k]-final)+((ll)1<<(k-1));
}
int main(){
int kase=0;
int n;
while(scanf("%d",&n)==1&&n){
for(int i=1;i<=n;i++)scanf("%d",&st[i]);
for(int i=1;i<=n;i++)scanf("%d",&ed[i]);
ll ans=0;
int k=n;
while(st[k]==ed[k]&&k>0)k--;
if(k>0){
ans=f(st,k-1,6-st[k]-ed[k])+f(ed,k-1,6-st[k]-ed[k])+1;
}
printf("Case %d: %lld\n",++kase,ans);
}
return 0;
}