终于考试完了,又可以学习啦!
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;
}