Learning pathOriginal reference
Lesson 9 of 12

Priority queues: choose the next extreme

Use max-heaps, min-heaps, and pair priorities without confusing heap order with full sorting.

Highest priority is not earliest arrival

std::priority_queue<int> exposes the greatest stored integer at top(). push inserts, pop removes one top occurrence, and size/empty inspect the state. Duplicates remain separate. top() reads without removing and provides read-only access to the key.

The adaptor has no general indexing, iteration, front/back, arbitrary erase, or direct priority update. Its heap structure guarantees the next extreme at the top; it does not expose a fully sorted internal array.

The comparator changes the selected end

A min-heap uses std::priority_queue<int, std::vector<int>, std::greater<int>>. Include <functional>, <queue>, and <vector>. push, pop, and top keep their names; the smallest value now has highest priority.

Pair ordering still applies. A default max-heap of (score, ID) prefers larger score and then larger ID. A min-heap of (time, ID) prefers smaller time and then smaller ID. Neither automatically implements higher score with smaller ID. A bounded key such as (score, −ID) can express that mixed rule only when negation is safe and the tie direction is checked.

C++23
// Complete C++23 program. No input; output: 9 2
#include <functional>
#include <iostream>
#include <queue>
#include <vector>
int main() {
    std::priority_queue<int> greatest;
    std::priority_queue<int, std::vector<int>, std::greater<int>> smallest;
    for (int x : {4, 9, 2, 9}) {
        greatest.push(x);
        smallest.push(x);
    }
    greatest.pop(); // Removes only one nine.
    std::cout << greatest.top() << ' ' << smallest.top() << '\n';
}

Count the updates, not just top()

top() is O(1). Heap repair for push and pop uses logarithmic comparisons. A single push may also trigger a linear reallocation of the default backing vector, so the usual O(log(n + 1)) push time is amortized over a sequence.

Building by n pushes and extracting all values takes O(1 + n log(n + 1)) time. If fixed input only needs sorted output once, vector plus sort is often simpler. A heap is especially useful when insertions alternate with requests for the current minimum or maximum.

Container workbench

Insert values, then remove the next accessible item. Priority queue values are shown sorted for explanation, not as an internal heap.

80
31
52

Next removal: 5. Size: 3.

Guided simulation · Change the inputs to test your understanding.

Pause & predict

A default max-priority queue of pairs contains (90, 2) and (90, 5). Which is top?

Choose an answer
Try it yourself

Turn the idea into code

Read n events as time ID, with nonnegative times and unique positive IDs. Print IDs in earlier-time order and smaller-ID order on ties. Use a min-priority queue of pairs; n may be zero.

Give me a hint

Store the fields as (time, ID), and use std::greater for that same pair type.

Show the explained solution

The minimum pair is exactly the earliest event with the required tie rule. Copy the top before popping. Individual pushes and all removals take O(1 + n log(n + 1)) total amortized time, with O(n + 1) storage.

C++23
// Complete C++23 program. Input: 0 <= n <= 200000, then time ID pairs.
#include <functional>
#include <iostream>
#include <queue>
#include <utility>
#include <vector>
int main() {
    int n = 0;
    std::cin >> n;
    using Event = std::pair<int, int>;
    std::priority_queue<Event, std::vector<Event>, std::greater<Event>> events;
    for (int i = 0; i < n; ++i) {
        int time = 0, id = 0;
        std::cin >> time >> id;
        events.push({time, id});
    }
    while (!events.empty()) {
        Event next = events.top();
        events.pop();
        std::cout << next.second << '\n';
    }
}

Your notes

Ready for the next idea?

Mark complete when you can explain it yourself.

From a problem to a programIdentify the input, output, and constraints, then translate a small plan into C++.Variables, types, and remembered valuesChoose a representation, initialize it, and understand what assignment really changes.Arithmetic without surprisesPredict division and remainder, widen before multiplication, and format decimal answers.Conditions and logical decisionsBuild exclusive categories, combine comparisons, and protect operations with short-circuit logic.Optional: other ways to chooseRecognize switch for exact choices and the conditional operator for choosing a value.For loops: make repetition preciseTrace initialization, condition, body, and update—and avoid an extra iteration.While, do-while, and stopping rulesChoose a loop from its stopping condition and read the exact input format.Break, continue, and early answersDistinguish leaving a loop from skipping one iteration, without losing required input.Five patterns worth understandingUse sums, counts, best-so-far candidates, products, and flags to process a stream.Nested loops: rows and columnsTranslate a shape into two loop roles and count the total work.Take a number apart, one digit at a timeUse remainder and division to process decimal digits, including zero.Multiple cases and a debugging mindsetCombine the patterns, isolate each case, and test the boundaries that can break your idea.Arrays: give every value a placeUnderstand indices, initialization, capacity, active length, and the first safe array loop.Scan, count, search, and compareDistinguish values from positions and preserve the exact tie rule a problem asks for.Change a sequence without losing itUpdate, copy, compare, reverse, and inspect neighbours using the correct bounds.Matrices: think in two coordinatesTraverse tables, total rows and columns, inspect diagonals, and protect grid neighbours.Characters become stringsSeparate characters from numbers, then safely inspect and edit managed text.Read the text the problem actually givesChoose words or full lines, preserve empty cases, and reset only the state that needs it.Scan text: count, filter, transformBuild a result from matching characters without losing leading zeros or skipping shifted text.Join, compare, and find textLearn content comparison, lexicographical order, substring counts, and the not-found sentinel.