新汉诺塔,洛谷之提高历练地,搜索Ex(3-1)

正题

      第六题:新汉诺塔

      这题的问题:

     1.怎么保证放好之后当前位置的点下面没有更小的点

     2.怎么通过第三根柱子把自己运到目标柱子上。

     解决方法:

     1.从大往小做,先处理大的在处理小的。

     2.把小于当前圆盘编号的圆盘先移动到第三根柱子,再把自己移动到目标柱子。

代码<挺短的>,变量名帮助理解(where,现在在哪)(shuold,应该在哪)

#include<cstdio>
#include<cstdio>
#include<cstring>

int n;
int where[50];
int should[50];
int ans=0;

void move(int x,int from,int to){
	printf("move %d from %c to %c\n",x,from+'A'-1,to+'A'-1);
	where[x]=to;
	ans++;
	return ;
}

void dfs(int x,int now,int target,int by){
	if(now==target) return ;
	for(int i=x-1;i>=1;i--)
		dfs(i,where[i],by,6-where[i]-by);
	move(x,now,target);
}

int main(){
	scanf("%d",&n);
	for(int i=1;i<=3;i++){
		int t;
		scanf("%d",&t);
		for(int j=1;j<=t;j++){
			int x;
			scanf("%d",&x);
			where[x]=i;
		}
	}
	for(int i=1;i<=3;i++){
		int t;
		scanf("%d",&t);
		for(int j=1;j<=t;j++){
			int x;
			scanf("%d",&x);
			should[x]=i;
		}
	}
	
	for(int i=n;i>=1;i--){
		if(where[i]==should[i]) continue;
		dfs(i,where[i],should[i],6-where[i]-should[i]);
	}
	printf("%d",ans);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值