Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
---|---|---|---|---|---|
3s | 8192K | 867 | 302 | Standard |
There is a famous railway station in PopPush City. Country there is incredibly hilly. The station was built in last century. Unfortunately, funds were extremely limited that time. It was possible to establish only a surface track. Moreover, it turned out that the station could be only a dead-end one (see picture) and due to lack of available space it could have only one track.
The local tradition is that every train arriving from the direction A continues in the direction B with coaches reorganized in some way. Assume that the train arriving from the direction A has N <= 1000 coaches numbered in increasing order 1, 2, ..., N. The chief for train reorganizations must know whether it is possible to marshal coaches continuing in the direction B so that their order will be a1, a2, ..., aN. Help him and write a program that decides whether it is possible to get the required order of coaches. You can assume that single coaches can be disconnected from the train before they enter the station and that they can move themselves until they are on the track in the direction B. You can also suppose that at any time there can be located as many coaches as necessary in the station. But once a coach has entered the station it cannot return to the track in the direction A and also once it has left the station in the direction B it cannot return back to the station.
5 1 2 3 4 5 5 4 1 2 3 0 6 6 5 4 3 2 1 0 0
Yes No Yes
/*这不是一个难题,我却犯了一个很二的错误,在递归调用find函数的时候忘记了
要将find函数用return语句返回。大体思路就是先将题目中所给出的数字的顺序
储存起来(store数组)然后用soure数组储存1,2,3,4,5,6,7.。。。。。然后将source
数组依次与store数组里面的数字比较,如果小于就放入栈中,如果等于看都往后移动
一个数字,如果大于则返回false*/
#include<cstdio>
#include<iostream>
#include<stack>
using namespace std;
stack<int>s;
int source[1002];
int store[1002];
int n;
bool find(int so,int st)
{
if(st>n)
{
return true;
}
else if(so<=n)
{
if(source[so]<store[st])
{
s.push(source[so]);
return find(so+1,st);
}
else if(source[so]>store[st])//从栈区取出一个数字
{
if(s.empty())return false ;
int m=s.top();
s.pop();
if(m!=store[st])return false;
else
{
return find(so,st+1);
}
}
else
{
return find(so+1,st+1);
}
}
else
{
while(!s.empty())
{
int m=s.top();
s.pop();
if(m!=store[st])
return false;
else
return find(so,st+1);
}
}
}
int main()
{
//freopen("in.txt","r",stdin);
//freopen("out.txt","w",stdout);
while(scanf("%d",&n),n)
{
while(scanf("%d",&store[1]),store[1])
{
while(!s.empty())
s.pop();
for(int i=1;i<=n;i++)
source[i]=i;
source[n+1]=0;
for(int i=2;i<=n;i++)
scanf("%d",&store[i]);
if(find(1,1))
printf("Yes\n");
else printf("No\n");
}
printf("\n");
}
return 0;
}