本題要求模擬火車調度:給定進站順序 (1..N),判斷給定的出站序列是否合法。棧 (站內軌道) 具有後進先出 (LIFO) 特性,是解題關鍵。
#include <cstdio>
#include <stack>
using namespace std;
int main() {
int N;
while (scanf("%d", &N) == 1 && N) {
while (true) {
int target[1005];
scanf("%d", &target[0]);
if (target[0] == 0) { puts(""); break; }
for (int i = 1; i < N; i++) scanf("%d", &target[i]);
stack st;
int next_in = 1;
bool ok = true;
for (int i = 0; i < N; i++) {
while (next_in <= N && (st.empty() || st.top() != target[i])) {
st.push(next_in++);
}
if (!st.empty() && st.top() == target[i]) st.pop();
else { ok = false; break; }
}
puts(ok ? "Yes" : "No");
}
}
return 0;
}
此題是棧模擬的經典入門,掌握「壓入直到滿足、否則失敗」模板,可解決大量類似調度、括號匹配、遞迴消除問題。