Files
exercises/dsa/ch3_stack_queue/dsa_0306_stack_operation.cpp
T
2026-09-28 14:05:06 +08:00

47 lines
1.1 KiB
C++

#include <iostream>
#include <stack>
#include <vector>
using Operation = std::pair<bool, int>;
int n, idx = 0;
std::stack<int> stack;
std::vector<int> sequence;
std::vector<Operation> operation_log;
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cin >> n;
operation_log.reserve(2 * n);
sequence.resize(n);
for (int i = 0; i < n; i++) {
std::cin >> sequence[i];
}
for (int current_num = 1; current_num <= n;) {
while ((stack.empty() || stack.top() != sequence[idx]) && current_num <= n) {
stack.push(current_num);
operation_log.emplace_back(false, current_num);
current_num++;
}
while (!stack.empty() && stack.top() == sequence[idx]) {
stack.pop();
operation_log.emplace_back(true, sequence[idx]);
idx++;
}
}
if (!stack.empty()) {
std::cout << "NO" << std::endl;
} else {
for (const auto [op, x] : operation_log) {
std::cout << (op ? "POP " : "PUSH ") << x << std::endl;
}
}
return 0;
}