题目描述
已知自然数1,2,...,N(1<=N<=100)依次入栈,请问序列C1,C2,...,CN是否为合法的出栈序列。
输入
输入包含多组测试数据。
每组测试数据的第一行为整数N(1<=N<=100),当N=0时,输入结束。
第二行为N个正整数,以空格隔开,为出栈序列。
输出
对于每组输入,输出结果为一行字符串。
如给出的序列是合法的出栈序列,则输出Yes,否则输出No。
样例输入
5 3 4 2 1 5 5 3 5 1 4 2 0
样例输出
Yes No
talk is cheap ,show me your code
#include<iostream>
#include<stack>
using namespace std;
int main() {
int x;
while (1) {
stack<int> st2;
stack<int> st3;
cin >> x;
if (x == 0) {
break;
}
int flag = 1;
for (int i = 1; i <= x; i++) {
int y;
cin >> y;
if (st2.empty()) {
st2.push(y);
}else if(st2.top()<y){
st2.pop();
st2.push(y);
}else if (st2.top() > y) {
if (st3.empty()) {
st3.push(y);
}
else if (st3.top() > y) {
st3.pop();
st3.push(y);
}
else if (st3.top() < y) {
flag = 0;
}
}
}
if (flag) {
cout << "Yes" << endl;
}
else {
cout << "No" << endl;
}
}
}