Uva 10795 A Different Task

题目链接: 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.
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 (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

(详细解析在代码中给出)

题目代码

#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
#define LL long long
LL f(int *P,int i,int final){
	if(i==0)return 0;
	if(P[i]==final)return f(P,i-1,final);//已经不需要再移动了 
	return f(P,i-1,6-P[i]-final)+(1LL<<(i-1));//还需要移动2^(i-1)步 
}
const int mxn=60+10;
int n,start[mxn],finish[mxn];
int main()
{
	int kase=0;
	while(scanf("%d",&n)&&n){
		printf("Case %d: ",++kase);
		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>=1&&start[k]==finish[k])--k;
		LL ans=0;
		if(k>=1){
			int other=6-start[k]-finish[k];
			ans=f(start,k-1,other)+f(finish,k-1,other)+1;
			//f表示把盘子1~k移动到other所需要的步数,而我们需要在移动到other之后
			//再将其移动到finish,而盘子的移动是可逆的,因此就相当于从final移动到
			//other所需要的的步数,再加上移动一个盘子的步数. 
		}
		printf("%lld\n",ans);
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值