有 n 輛火車 (n≤9),給定進棧序列和出棧序列,判斷出棧序列是否合法。合法則輸出操作序列(in/out),否則輸出 No。
用棧模擬進出過程:
#include#include #include using namespace std; int main() { int n; char in[10], out[10]; while (cin >> n >> in >> out) { stack s; int j = 0, k = 0; char ops[20]; // 記錄操作 for (int i = 0; i < n; i++) { s.push(in[i]); ops[k++] = 'i'; // in while (!s.empty() && j < n && s.top() == out[j]) { s.pop(); ops[k++] = 'o'; // out j++; } } if (s.empty()) { cout << "Yes." << endl; for (int i = 0; i < k; i++) cout << (ops[i]=='i' ? "in" : "out") << endl; cout << "FINISH" << endl; } else { cout << "No." << endl << "FINISH" << endl; } } return 0; }