#C14443. Priority Queue Operations
Priority Queue Operations
Priority Queue Operations
You are required to implement a priority queue using a binary heap that supports three primary operations:
- INSERT <item> <priority>: Insert an element named
item
with an integerpriority
into the queue. If the item already exists, update its priority by replacing the old value. - EXTRACT: Remove and print the item with the highest priority. In case of a tie, the item that was inserted earlier (i.e. with a smaller insertion order counter) is considered to have higher precedence. If the queue is empty, print
error
. - INCREASE <item> <new_priority>: Increase the priority of the given
item
tonew_priority
only ifnew_priority
is greater than the current priority. If the specified item does not exist in the queue, printerror
. If the new priority is not higher, do nothing.
You will receive the commands as input from stdin and should output responses to stdout. Only the EXTRACT
operations (and error messages from failed operations) produce output.
Note: It is guaranteed that the number of commands is a positive integer. Use efficient methods to ensure your implementation passes within time limits.
inputFormat
The first line contains an integer Q
representing the number of commands. Each of the next Q
lines contains one command in one of the following formats:
INSERT <item> <priority>
EXTRACT
INCREASE <item> <new_priority>
Items are strings without spaces and priorities are integers.
outputFormat
For each EXTRACT
command, output a line containing the extracted item. Additionally, if an EXTRACT
command is issued when the queue is empty or an INCREASE
command is attempted on a non-existent item, output a line with error
.
7
INSERT apple 3
INSERT banana 2
INSERT cherry 5
EXTRACT
INCREASE banana 6
EXTRACT
EXTRACT
cherry
banana
apple
</p>