如图,n节车厢从A方向入站,进站顺序编号1~n,判断能否按照特定顺序从B出站。C是中转站,后入先出。
数组实现:
#include<stdio.h>
#include<stdlib.h>
#define maxn 5000
int n,target[maxn],c[maxn];
int main(){
//freopen("stack.in","r",stdin);
while(scanf("%d",&n)==1){
int A=1,B=1,top=0,i,ok;
for(i=1;i<=n;i++)
scanf("%d",&target[i]);
ok=1;
while(B<=n){
if(A==target[B])
{
++A;
++B;
}
else if(top&&c[top]==target[B])
{
top--;
B++;
}
else if(A<=n)
c[++top]=A++;
else
{
ok=0;
break;
}
}
printf("%s\n",ok?"Yes":"No");
}
return 0;
}
STL实现
#include<iostream>
#include<stack>
#define MAXN 5000
using namespace std;
int main(){
//freopen("stack.in","r",stdin);
int target[MAXN],n;
while(cin>> n){
stack<int> s;
for(int i=1;i<=n;i++)
cin >> target[i];
int A=1,B=1,ok=1;
while(B<=n){
if(A==target[B])
{
A++;
B++;
}
else if(!s.empty()&&target[B]==s.top())
{
s.pop();
B++;
}
else if(A<=n)
s.push(A++);
else
{
ok=0;
break;
}
}
if(ok)
cout << "Yes";
else
cout <<"No";
cout << endl;
}
return 0;
}