正题
第六题:新汉诺塔
这题的问题:
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);
}