Overflowing Bookshelf
InterviewTime limit1sMemory limit128 MB
Simulate a fixed-width shelf through add (push books leftward) and remove events; at End list the surviving books left to right.
- Level
Medium5 of 10
- Topics
- Simulation, Implementation, Array, Linked list
- Solved
- No attempts yet
Problem
Simulate a bookshelf of fixed width. Over time books are put on the shelf and taken off it; at the end you report the books that remain, listed from left to right.
Each book is identified by a distinct positive integer id with , and has an integer width. The shelf processes three kinds of events:
- Add: A new book is pushed onto the left end of the shelf, sliding the other books to the right as needed. A book moves to the right only when it is pushed by an adjacent (touching) book on its immediate left; a book that is not touched does not move. Any book that ends up not entirely on the shelf falls off the right edge and is gone. No single book is ever wider than the shelf, and a book already on the shelf is never added again.
- Remove: If the given book is on the shelf, it is taken off, leaving an empty gap where it was (the other books keep their positions). If the book is not on the shelf, the event is ignored.
- End: Finish the current simulation and report the books left on the shelf, from left to right.
Input
The input contains one or more simulations. A line containing only marks the end of the input.
Each simulation starts with a line holding the shelf width with , followed by a sequence of events, one per line:
- An add event is a line that starts with an uppercase
A, then the book id, then the book width with . - A remove event is a line that starts with an uppercase
R, then the book id. - The end event is a line containing a single uppercase
E.
Within an event, each number is preceded by exactly one space.
Output
For each simulation, print one line: the label PROBLEM k: (where is the simulation number, starting at ), followed by the ids of the books remaining on the shelf, from left to right, each preceded by a single space. If the shelf is empty, print only the label.