站点图标 陌路寒暄

汉诺塔(栈和队列)

汉诺塔(栈和队列)

时间: 1ms        内存:128M

描述:

1.有三根杆子A,B,C。A杆上有若干碟子 
2.每次移动一块碟子,小的只能叠在大的上面 
3.把所有碟子从A杆全部移到C杆上

输入:

3

输出:

7

示例输入:

4

示例输出:

15

提示:

参考答案(内存最优[748]):

#include<stdio.h>
#include<stdlib.h>
int time=0;
void compute(int n,int x,int y,int z)
{
	if(n==1)
		time++;
	else{
		compute(n-1,x,z,y);
		time++;
		compute(n-1,y,x,z);
	}
}
int main()
{
	int n,x=1,y=2,z=3;
	scanf("%d",&n);
	compute(n,x,y,z);
	printf("%d",time);
	return 0;
}

参考答案(时间最优[0]):

#include<stdio.h>
#include<stdlib.h>
int time=0;
void compute(int n,int x,int y,int z)
{
	if(n==1)
		time++;
	else{
		compute(n-1,x,z,y);
		time++;
		compute(n-1,y,x,z);
	}
}
int main()
{
	int n,x=1,y=2,z=3;
	scanf("%d",&n);
	compute(n,x,y,z);
	printf("%d",time);
	return 0;
}

题目和答案均来自于互联网,仅供参考,如有问题请联系管理员修改或删除。

退出移动版