​题目地址​

输入

5
1 2 3 4 5
5 4 1 2 3
0
6
6 5 4 3 2 1
0
0

输出

Yes
No

Yes

思路:栈的使用
A表示车厢序号,target数组表示列车出站的序号(理想情况).B用来表示已经出站的车辆数(实际).
中转站用​​​Statck<int>​​​ s表示
1.A中元素==B中元素,A直接驶入B
2.A中首元素!=B中元素,栈首元素 == B首元素,栈首元素出栈.
3.A中首元素!=B中元素, 栈首元素 != B首元素, A中元素个数大于 0,A中元素进入栈.
4.A中首元素!=B中元素, 栈首元素 != B首元素, A中元素个数 <=0 ,该解不成立.

输入输出形式要注意.

参考代码

#include<bits/stdc++.h>
using namespace std;
const int maxsize = 1000;
int target[maxsize + 10],n,A,B,ok;//target:存放需要判断的出站的序列.
stack<int> s;
int main()
{
while (cin >> n && n) {
while (1) {
stack<int> s;
cin >> target[1];
if (!target[1]) {
break;
}
ok = 1;
A = 1;//记录表示入站的车厢序号
B = 1;//记录已经驶出车站的车厢数
for (int i = 2; i <= n; i++) {
cin >> target[i];
}
while (B <= n) {
if (A == target[B])//A中首元素=B中首元素
{
A++;
B++;
}
else if (!s.empty() && s.top() == target[B]) {//A中首元素!=B中首元素 ,s不为空但栈首元素相等.
B++;
s.pop();
}
else if (A <= n)//A中首元素!=B中首元素 s为空 ,A中仍有元素
{
s.push(A++);//元素进栈
}
else {
ok = 0;
break;
}


}
if (ok) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
cout << endl;
}
return 0;
}