#C298. Max Tracking Stack
Max Tracking Stack
Max Tracking Stack
You are required to implement a stack data structure that supports the following operations in O(1) time:
- push X: Push an integer X onto the stack.
- pop: Remove the top element of the stack and print it. If the stack is empty, print
Empty Stack
. - top: Print the top element of the stack without removing it. If the stack is empty, print
Empty Stack
. - get_max: Print the maximum element in the stack. If the stack is empty, print
Empty Stack
. - is_empty: Print
True
if the stack is empty, andFalse
otherwise.
The operations should be processed sequentially from standard input. The first line of input contains an integer representing the number of operations. Each subsequent line contains one operation.
Note: When an operation that returns a value is executed (pop
, top
, get_max
, is_empty
), the corresponding result should be printed on a new line.
The underlying idea is to design the stack such that the maximum element at any point can be retrieved in constant time. One common approach is to use an auxiliary stack to keep track of the maximum values. Mathematically, if we denote the auxiliary max stack as \( M \) and the main stack as \( S \), then upon each push operation with value \( x \), we update \( M \) as follows:
\[ M.push(\max(x, M.top())) \quad \text{if } M \text{ is not empty; otherwise } M.push(x). \]This ensures that \( M.top() \) always reflects the maximum element of \( S \).
inputFormat
The input begins with an integer N
(\(1 \leq N \leq 10^5\)), representing the number of operations. The following N
lines each contain one of the following operations:
- push X — where
X
is an integer. - pop
- top
- get_max
- is_empty
Each operation is given on a separate line via standard input.
outputFormat
For each operation that returns a value (pop
, top
, get_max
, is_empty
), print the result on a separate line on standard output. If an operation is invoked on an empty stack (for pop
, top
, or get_max
), print Empty Stack
.
6
push 5
push 1
push 7
get_max
pop
get_max
7
7
5
</p>