題意:有一鐵軌如下圖,有n節車廂從A方向駛入車站,按進站順序編號1~n,A中進入C的車廂不能再返回A,C中進入B的車廂也不能再返回C。讓你判斷能否按某特定順序進如B方向的鐵軌,並駛出車站。
分析:鐵軌的中轉站C是關鍵,先駛入C的車廂後出,很明顯符合棧先進後出的原則,用棧模擬一下即可。任意時刻,只有兩種選擇,A->C和C->B,當第i節車廂進入C時,判斷是否是給定順序中的下一節車廂,如果是,則出站,並繼續判斷C中棧頂車廂,如果不是,則A中下一節車廂進C。
#include <iostream>
#include <string>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <stack>
using namespace std;
const int MAXN=1010;
int n,tar[MAXN];
int main()
{
//freopen("in.txt","r",stdin);
while(cin>>n&&n)
{
stack<int> s;
while(cin>>tar[1]&&tar[1])
{
for(int i=2; i<=n; i++)
cin>>tar[i];
int ok=1,a=1,b=1;
while(b<=n)
{
if(a==tar[b]){ a++;b++; }
else if(!s.empty()&&s.top()==tar[b]) { s.pop(); b++; }
else if(a<=n) { s.push(a);a++; }
else{ ok=0; break; }
}
if(ok) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
cout<<endl;
}
return 0;
}