Answer the question
In order to leave comments, you need to log in
What is wrong with implementing a queue with a minimum?
There is a task:
Minimum-aware queue Implement a minimum
-aware queue.
Specifications Input
The first line of the input contains the number n — the number of operations with the queue. Each next line contains the number a (0≤a≤10000). If a>0, then this number must be added to the queue. If a=0, then this is a request to remove an element from the queue.
Output
For each request to remove an element from the queue, it is necessary to display the value of the minimum element of the queue (taking into account the value of the element being removed). If the delete request is called on an empty queue, then print -1.
class Stack_min:
def __init__(self):
self.stack = []
self.stack_min = []
def push(self, e):
self.stack.append(e)
if self.stack_min and self.stack_min[-1] < e:
self.stack_min.append(self.stack_min[-1])
else:
self.stack_min.append(e)
return self
def pop(self):
if self.stack != []:
self.stack_min.pop()
return self.stack.pop()
def min(self):
if self.stack_min:
return self.stack_min[-1]
def aslist(self):
return self.stack
def back(self):
if self.stack != []:
return self.stack[-1]
def size(self):
return len(self.stack)
def clear(self):
self.stack.clear()
self.stack_min.clear()
return self
class Queue_min:
def __init__(self):
self.s1 = Stack_min()
self.s2 = Stack_min()
def _copy(self):
if self.s2.size() == 0:
while self.s1.size():
self.s2.push(self.s1.pop())
def push(self, e):
self.s1.push(e)
return self
def pop(self):
self._copy()
return self.s2.pop()
def front(self):
self._copy()
return self.s2.back()
def size(self):
return self.s1.size() + self.s2.size()
def min(self):
self._copy()
return self.s2.min()
def clear(self):
self.s1.clear()
self.s2.clear()
return self
queue = Queue_min()
for i in range(int(input())):
inp = int(input())
if inp != 0:
queue.push(inp)
else:
if not queue.size():
print(-1)
else:
print(queue.min())
queue.pop()
Answer the question
In order to leave comments, you need to log in
When calculating the minimum, you only consider one of the two stacks, and the minimum can be in either of the two. Consider this test with 7 queries:
7
5
6
7
0
1
2
0
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question