现在的位置: 首页 > 综合 > 正文

NYOJ - 汉诺塔(三)

2017年06月04日 ⁄ 综合 ⁄ 共 1145字 ⁄ 字号 评论关闭
93 汉诺塔(三)

定义一个栈一维数组,包含3个栈,代表3个柱子,依次执行指令
第一次提交时,注释什么多余的语句没删除,每个栈开的长度大了,提交结果 内存 972
然后将神马多余的都删除,栈长度改的正合适,提交结果 内存 308
[code]
 
#define TRUE 1
#define FALSE 0
#define STACK_INIT_SIZE 66
#include "iostream"
#include "cstdlib"
#include "cstdio"
#include "cstring"
using namespace std;
typedef int Status; //Status 相当于 int
typedef int ElemType;
typedef struct Stack
{
ElemType * base, * top;
}SqStack;
void  InitStack(SqStack &S)
//创建一个空栈
{
S.base = (ElemType *)malloc(sizeof(ElemType) *
STACK_INIT_SIZE);
S.top = S.base;
}
Status StackEmpty(SqStack S)//判断是否为空
{
if(S.top == S.base) return TRUE;
else return FALSE;
}
void Push(SqStack &S,ElemType e
)//插入元素e为新的栈顶元素
{
* S.top++ = e;
}
void Pop(SqStack &S,ElemType
&e)//出栈
{
e = * --S.top;
}
ElemType GetTop(SqStack S)
{
return *(S.top-1);
}
int main()
{
int n;
scanf("%d",&n);
while(n--){
int p,q;
scanf("%d%d",&p,&q);
SqStack S[3];//定义3个栈,代表3个柱子
InitStack(S[0]); InitStack(S[1]); InitStack(S[2]);
for(int i=p; i>=1; i--)
Push(S[0],i);//第一步,初始化1柱上的金片
int flag = 1;
int a,b,e;
for(int i=0; i<q; i++)//Q条指令
{
scanf("%d%d",&a,&b);//从a柱到b柱
if(StackEmpty(S[a-1]))  { flag = 0;
break;}
else Pop(S[a-1],e); 
if(!StackEmpty(S[b-1]) &&
e>GetTop(S[b-1]))  { flag = 0;
break;}
else Push(S[b-1],e);
}
if(flag) printf("legal\n");
else printf("illegal\n");
}
return 0;
}      
 
[\code]

抱歉!评论已关闭.