#C14725. Implementing a Priority Queue using a Binary Heap
Implementing a Priority Queue using a Binary Heap
Implementing a Priority Queue using a Binary Heap
In this problem, you are required to implement a priority queue with the following operations:
insert <task> <priority>
: Insert a task with a given integer priority.peek
: Return the task with the maximum priority without removing it.extract
: Remove and return the task with the maximum priority.
The priority queue must be implemented using a binary max-heap. In a binary heap, for a node at index \(i\), the parent's index is \(\lfloor (i-1)/2 \rfloor\) and its children are at indices \(2i+1\) and \(2i+2\).
If an operation that returns an element (i.e. peek
or extract
) is called on an empty queue, print "error".
inputFormat
The first line contains an integer n
denoting the number of commands.
The following n
lines each contain a command. Each command is one of the following formats:
insert <task> <priority>
where<task>
is a string (with no spaces) and<priority>
is an integer.peek
extract
outputFormat
For every command peek
or extract
, output the resulting task in a new line. If the queue is empty when performing peek
or extract
, output "error" (without quotes).
7
insert task1 2
insert task2 5
insert task3 1
peek
extract
extract
extract
task2
task2
task1
task3
</p>