High-Performance Stack Implementation in C++
This problem requires the implementation of a standard Last-In-First-Out (LIFO) stack capable of processing a high volume of operations efficiently. The solution must handle multiple independent test cases.
Core Functional Requirements
The data structure must support the following commands:
- push(x): Append an integer
xto the top of the stack. - pop(): Remove the top element. If the structure is empty, output "Empty".
- query(): Inspect the top element without removal. If the structure is empty, output "Anguei!".
- size(): Return the current number of elements in the structure.
Performance Considerations
Given the constraints where the total number of operations can reach $10^6$, standard input/output methods in C++ may become a bottleneck. It is critical to disable synchronization with the C standard libraries to achieve acceptable performance.
C++ Implementation
The following code utilizes the STL std::stack adapter. By declaring the stack instance within the test case loop, memory is automatically reset or reused, satisfying the requirement to start with an empty stack for each dataset.
#include <iostream>
#include <stack>
#include <string>
// Optimization for high-speed I/O
void accelerate_io() {
std::ios_base::sync_with_stdio(false);
std::cin.tie(nullptr);
}
int main() {
accelerate_io();
int test_cases;
if (!(std::cin >> test_cases)) return 0;
while (test_cases--) {
std::stack<long long> buffer;
int op_count;
std::cin >> op_count;
while (op_count--) {
std::string operation;
std::cin >> operation;
if (operation == "push") {
long long value;
std::cin >> value;
buffer.push(value);
}
else if (operation == "pop") {
if (buffer.empty()) {
std::cout << "Empty\n";
} else {
buffer.pop();
}
}
else if (operation == "query") {
if (buffer.empty()) {
std::cout << "Anguei!\n";
} else {
std::cout << buffer.top() << "\n";
}
}
else if (operation == "size") {
std::cout << buffer.size() << "\n";
}
}
}
return 0;
}