有n辆火车入栈出栈,判断出栈顺序是否合法
逆向思维,将出栈后的火车重新入栈看能否构成1-n
用a,b两个变量标记,将a入栈直到找到第一个t[a] == b的数,然后判断栈内的数与t[b]是否匹配。
#include <cstdio>
#include <stack>
using namespace std;
int t[1005];
int main(int argc, char const *argv[]) {
int n;
while (scanf("%d", &n) == 1 && n) {
while (scanf("%d", &t[1]) == 1 && t[1]) {
for (int i = 2; i <= n; i++) {
scanf("%d", &t[i]);
}
stack<int> s;
int a = 1, b = 1;
bool ok = true;
while (b <= n) {
if (a == t[b]) {
a++;
b++;
} else if (!s.empty() && s.top() == t[b]) {
s.pop();
b++;
} else if (a <= n) {
s.push(a++);
} else {
ok = false;
break;
}
}
if (ok) {
puts("Yes");
} else {
puts("No");
}
}
putchar('\n');
}
return 0;
}