#C11577. Priority Message Queue
Priority Message Queue
Priority Message Queue
You are required to implement a priority message queue supporting four operations. The queue stores messages each paired with an integer priority. Higher integer values indicate higher priority. In case two messages share the same priority, the message inserted earlier should be dequeued first.
The supported operations are:
- enqueue p message: Insert a message with priority p and content message into the queue.
- dequeue: Remove and print the message with the highest priority. If the queue is empty, print "The queue is empty.".
- peek: Print the message with the highest priority without removing it from the queue. If the queue is empty, print "The queue is empty.".
- is_empty: Print "True" if the queue is empty; otherwise, print "False".
Commands are given via standard input. When processing, output the result of the commands dequeue
, peek
, and is_empty
each on a new line.
Note: The operation enqueue
does not produce any output.
Implementation Detail:
To achieve the desired behavior, you may use a max-heap (or priority queue with a custom comparator) where the primary key is the priority (in descending order) and the secondary key is the order of insertion (in ascending order). If necessary, use LaTeX for formulas (e.g., $priority_1 > priority_2$) in your explanation.
inputFormat
The first line of input contains an integer , representing the number of commands. Each of the following lines contains a command. The commands can be any of the following:
enqueue p message
— Insert a message with integer priorityp
and contentmessage
into the queue. Note thatmessage
may consist of one or more words.dequeue
peek
is_empty
Read input from standard input.
outputFormat
For every command among dequeue
, peek
, and is_empty
, output the result on a separate line to standard output. If an operation is invoked on an empty queue (for dequeue
or peek
), output "The queue is empty.". For is_empty
, output either "True" or "False".## sample
7
enqueue 5 Message1
enqueue 1 Message2
peek
dequeue
is_empty
dequeue
dequeue
Message1
Message1
False
Message2
The queue is empty.
</p>