题意就是在汉诺塔基础上加上起始和终止状态,求需要的步数。
一开始让我写这道题,我是不会的。。。不过看了书上讲解,还是似懂非懂,利用一个函数f(P,i,final),P数组是各盘子初始柱子编号,i代表将1,2,3....i全部移到fianl柱子所需要的步数,呃,想清楚这个函数,然后递归求解就ok了,递归方程是f(P,i,final) = f(P,i-1,6-P[i]-final)+2的i-1次方
以下是代码:
#include<cstdio>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include <iostream>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#define INF 0x3f3f3f3f
#define maxn 100010
using namespace std;
long long f(int p[77],int i,int Final)
{
if(!i)
return 0;
if(p[i] == Final)
return f(p,i-1,Final);
return f(p,i-1,6-p[i]-Final) + (1ll << (i-1));
}
int n,start[77],finish[77];
int main()
{
int C = 1;
while(scanf("%d",&n) && n)
{
for(int i = 1; i <= n; i++)
scanf("%d",&start[i]);
for(int i = 1; i <= n; i++)
scanf("%d",&finish[i]);
int k = n;
while(k && start[k] == finish[k])
k--;
long long ans = 0;
if(k)
{
int other = 6 - start[k] - finish[k];
ans = f(start,k-1,other) + f(finish,k-1,other) + 1;
}
printf("Case %d: %lld\n",C++,ans);
}
return 0;
}