poj 1363

终于考试完了,又可以学习啦!

poj1363,这道题是数据结构与算法中的经典问题,给定一组进栈顺序,问栈有多少种出去的顺序,而这个题是选择题中常考“下列出栈顺序中不合法的是?”。

拿到之后最直接的思路就是模拟进出栈,代码AC了,但是时间为94ms。感觉不应该啊,这么简单的题,必定有更高效的算法。

可是怎么更高效呢?

/*
 * =====================================================================================
 *
 *       Filename:  1363.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2011年12月27日 16时09分08秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  MaZheng (blog.csdn.net/mazheng1989), mazheng19891019@gmail.com
 *        Company:  Dalian University Of Technology
 *
 * =====================================================================================
 */


#include<stdio.h>

#define	NUM 1005			/*  */
//please declare parameters here.
char input[NUM];
int output[NUM];
int stack[NUM];
//please declare functions here.

int main()
{
	 if(freopen("input.txt","r",stdin)==NULL) perror("Can not open the input file!");
	 
	//input your ...
	int N;
	int i,j;
	int top;
	while(scanf("%d",&N)&&N!=0)
	{
		while(scanf("%d",&output[1])&&output[1]!=0)
		{
		for(i=0;i<=N;i++)
			input[i]=0;
		top=0;
			for(i=2;i<=N;i++)
			{
			scanf("%d",&output[i]);
			}
/*			for(i=1;i<=N;i++)
				printf("%d ",output[i]);
			printf("\n");
*/
			for(i=1;i<=N;i++)
			{
				for(j=1;j<=output[i];j++)
				{
					if(input[j]==0)
					{
						stack[top++]=j;
						input[j]=1;
					}
				}
				if(top<=0||stack[--top]!=output[i])
				{
					break;
				}
			}
			if(i!=N+1)
			{
				printf("No\n");
//				printf("%d %d\n",i,top);
			}
			else
			{
				printf("Yes\n");
			}
		}
		printf("\n");
	}

	return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值