有三根杆子(tower)A,B,C。A杆上有N个穿孔圆盘(disk),盘的尺寸由下到上依次变小。要求按下列规则将所有圆盘移至C杆:
(1)每次只能移动一个圆盘;
(2)大盘不能叠在小盘上面。
/*hanoi.h*/ #include <assert.h> #include <stdio.h> #include <stdlib.h> extern int cnt; void move(int n,char a,char b,char c);
/*main.c*/ #include "hanoi.h" int cnt=0; int main() { int n; printf("%s","input the number of tower:"); scanf("%d",&n); assert(n>0); move(n,'A','B','C'); return 0; }
/*move.c*/ #include "hanoi.h" void move(int n,char a,char b,char c) { if(n==1) { ++cnt; printf("%s%2d:%s%d%s%c%s%c.\n","step ",cnt," move disk ",1," from tower ",a," to tower ",c); } else { move(n-1,a,c,b); ++cnt; printf("%s%2d:%s%d%s%c%s%c.\n","step ",cnt," move disk ",n," from tower ",a," to tower ",c); move(n-1,b,a,c); } }
1958 | Accepted | 156K | 0MS | C | 448B | 2013-08-30 10:16:20 |
#include "stdio.h" #define N 13 int main() { int i,k; int hanoi3[N],hanoi4[N]; /*initialization*/ hanoi3[1]=1; hanoi4[1]=1; /*compute hanoi3*/ for(i=2;i<N;i++) hanoi3[i]=2*hanoi3[i-1]+1; printf("%d\n",hanoi4[1]); for(i=2;i<N;i++) { hanoi4[i]=2+hanoi3[i-1]; for(k=1;k<i;k++) if(hanoi4[i]>2*hanoi4[k]+hanoi3[i-k]) hanoi4[i]=2*hanoi4[k]+hanoi3[i-k]; printf("%d\n",hanoi4[i]); } return 0; }
3601 | Accepted | 164K | 0MS | C | 392B | 2013-08-30 17:59:16 |
#include "stdio.h" #define MAX 101 int main() { int i,n,m; int a[MAX],b[MAX],c[MAX]; while(~scanf("%d%d",&n,&m)) { for(i=1;i<=n;i++) scanf("%d",&a[i]); b[1]=a[1]; c[1]=2*(a[1]-1)+1; for(i=2;i<=n;i++) { b[i]=(2*b[i-1]+a[i])%m; if(a[i]==1) c[i]=b[i]; else c[i]=(2*b[i-1]+2*a[i]+c[i-1])%m; } printf("%d\n",c[n]); } return 0; }