# Python program to implement k stacks in an array. class kStacks: # Constructor to initialize kStacks def __init__(self, n, k): self.n = n self.k = k self.arr = [0] * n self.top = [-1] * k self.next = [0] * n # Initialize all spaces as free self.freeIndex = 0 for i in range(n - 1): self.next[i] = i + 1 # -1 is used to indicate end of free list self.next[n - 1] = -1 # Function to push element x into # m'th stack def push(self, x, m): # Check if we have space for a new element if self.freeIndex == -1: return False # Store index of first free slot i = self.freeIndex # Update free to point to next slot in free list self.freeIndex = self.next[i] # Update next of top and then top for stack m self.next[i] = self.top[m] self.top[m] = i # Store the item in array self.arr[i] = x return True # Function to pop top element from # m'th stack. def pop(self, m): # Check if stack is empty if self.top[m] == -1: return -1 # Find index of top item in stack m i = self.top[m] # Update top of stack m self.top[m] = self.next[i] # Add the previous top to free list self.next[i] = self.freeIndex self.freeIndex = i # Return the popped element return self.arr[i] if __name__ == "__main__": n, k = 5, 4 s = kStacks(n, k) # Each query is of either 2 types # 1: Push operation -> {1, x, m} # 2: Pop operation -> {2, m} queries = [ [1, 15, 0], [1, 25, 1], [1, 35, 2], [1, 45, 3], [1, 55, 0], [2, 0], [2, 1], [1, 55, 0], [2, 3] ] for q in queries: if q[0] == 1: if s.push(q[1], q[2]): print(1, end=" ") else: print(0, end=" ") else: print(s.pop(q[1]), end=" ")