题目描述
给定 $n$ 个数字,已知这些数字的入栈顺序为 $1,2,⋯,n$,给定一个出栈顺序 $a_1,a_2,⋯,a_n$,请判断它是否是一个合理的出栈顺序。
如出栈顺序为4 5 3 2 1
,对应的栈操作为
1 入栈
2 入栈
3 入栈
4 入栈
4 出栈
5 入栈
5 出栈
3 出栈
2 出栈
1 出栈
输入描述
第一行:单个整数 $n$;
第二行:$n$ 个整数表示 $a_1,a_2,⋯,a_n$
数据范围
- $1≤a_i≤n$
- 对于30%的数据,$1≤n≤20$;
- 对于60%的数据,$1≤n≤2,000$;
- 对于100%的数据,$1≤n≤100,000$;
输出描述
如果合法,输出Valid
,否则输出Invalid
输入样例
5
4 5 3 2 1
输出样例
Valid
#include <iostream>
#include <cmath>
#include <stack>
using namespace std;
int n, x;
stack<int>stak;
int main() {
std::ios::sync_with_stdio(false);
cin >> n;
for(int i = 1; i <= n; i++) {
int tmp;
cin >> tmp;
if(stak.empty() && x <= tmp) {
while(x < tmp)
stak.push(x++);
x++;
}
else if(stak.top() == tmp)
stak.pop();
else if(stak.top() < tmp) {
while(x < tmp)
stak.push(x++);
x++;
}
else if(stak.top() > tmp) {
cout << "Invalid" << endl;
return 0;
}
}
cout << "Valid" << endl;
return 0;
}