輸入
分塊,每塊第一行:列車數;接下來:列車順序;最後一行:0
結束標誌:該塊只有0
輸出
分塊輸出,塊之間用空格隔開
分析
此類題可以用棧的方式來解決,共分爲以下幾種情況:
- (1)A->B,此時進入的列車序號正好等於要求的列車序號中的當前序號,直接出去
- (2)Station->B,此時Station最上面的列車序號等於要求的列車序號中的當前序號,從Station出去(出棧)
- (3)A->Station,此時進入的列車序號不等於要求的列車序號中的當前序號,需要進入Station等待(進棧)
- (4)如果不符合上述三種情況,則說明無解
代碼
#include <cstdio>
#include <stack>
using namespace std;
int main(){
int n,t,j;
int A,B;//A表示當前車廂序號(從1開始遞增),B表示對應目標在target中的下標
int ok;
int target[1010];//存放目標序列
while(scanf("%d",&n)==1){//一個塊
stack<int> s;
if(n==0){//結束標誌
break;
}
else{
while(1){
ok=1;
A=B=1;
scanf("%d",&t);//查看第一個數是否爲0
if(t==0){
printf("\n");
break;
}
else{
target[0]=t;
for(j=1;j<n;j++)
scanf("%d",&target[j]);
while(B<=n){
if(A==target[B-1]){//情況1
A++;
B++;
}
else if(!s.empty()&&s.top()==target[B-1]){//情況2
s.pop();
B++;
}
else if(A<=n){//情況3
s.push(A++);
}
else{
ok=0;
break;
}
}
printf("%s\n",ok?"Yes":"No");
}
}
}
}
return 0;
}