题目链接:
题意:
一列火车在如车站前,车厢入栈时默认是1,2,3,4,5…到n这样排列的。以0 为一块与一块的分界线。0 0表示结束。
输入想要出站后看到的排列,看通过在车站里进行入站,出站操作能否达到自己想要的排列。
stack是一个先进后出,函数正好可以满足条件。
输入样例:
5
1 2 3 4 5
5 4 1 2 3
0
6
6 5 4 3 2 1
0
0
输出样例:
Yes
No
Yes
题解以及代码思路如下:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
#include<math.h>
#include<algorithm>
#include<iostream>
using namespace std;
int main() {
int n;//车厢的个数
int outbound[2000];//储存出站时想怎样排列的数组。
while(scanf("%d",&n)&&n) {
stack<int> s;//车站,用于进行比对。
cin>>outbound[1];//从第一位开始。
while(outbound[1]) {//为0时进行下一块。
for(int i=2; i<=n; i++) cin>>outbound[i];
int count=1;//用于记录栈中成功比对的个数 + 1 ;
for(int i=1; i<=n; i++) {
s.push(i);//入栈前的车厢排列;
while(!s.empty()&&outbound[count]==s.top()) {//和最上边的进行比对。
s.pop();//比对成功最上边的一位弹出;
count++;
}
}
if(count-1==n) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
memset(outbound,0,sizeof(outbound));
cin>>outbound[1];
}
cout<<endl;
}
return 0;
}