能否让火车以规定顺序出栈?
有n节车厢从A驶入车站,按进站编号为1-n。你的任务是让他们按照某种特定的顺序进入B放下过的铁轨并驶出。为了重组车厢,你可以借助中转站statiom。这是一个可以停放任意多节车厢的车站,但是由于末端封顶,驶入station的车厢必须按照相反顺序驶出station。对于每个车厢,一旦从A移入station,就不能在回到A了;一旦station移入B,就不能回到Station了。
输入
多组数据 每组数据包裹2行,第一行为车厢节数n,接下来的1行是某种特定的顺序
输出
是否可以按照该顺序驶出 是输出Yes 否输出No
样例输入
5
1 2 3 4 5
5 4 1 2 3
0 //表示5结束
6
6 5 4 3 2 1
0 //表示6结束
0 //表示程序结束
样例输出
Yes
No
Yes
#include <cstdio>
#include <queue>
#include <stack>
using namespace std;
bool check_is_valid_order(queue<int> &order){
stack<int> S;
int n = order.size();
for(int i=1;i<=n;i++){
S.push(i);
while(!S.empty() && order.front() == S.top()){
S.pop();
order.pop();
}
}
if(!S.empty())
return false;
else
return true;
}
int main()
{
int n;
int train;
scanf("%d",&n);
while(n){
scanf("%d",&train);
while(train){
queue<int> order;
order.push(train);
for(int i=1;i<n;i++)
{
scanf("%d",&train);
order.push(train);
}
if(check_is_valid_order(order)){
printf("Yes\n");
}
else{
printf("No\n");
}
scanf("%d",&train);
}
printf("\n");
scanf("%d",&n);
}
return 0;
}