Lesson 4 of 12

Every copy counts

Use multisets to represent stock and sell exactly one affordable item.

Multiplicity changes the model

A multiset retains repeated copies. For {2, 5, 5, 5, 7}, size() is 5 and count(5) is 3. Each insert creates a new entry and returns an iterator; unlike set insertion, it does not return a pair with a new-key flag.

find(x) locates a matching occurrence, without promising the first one in an equal run. lower_bound(x) finds the run’s beginning. equal_range(x) returns lower and upper bounds, whose half-open interval contains every matching copy.

Erase one copy or all copies deliberately

bag.erase(x) removes every copy matching key x. To remove one occurrence, find x, verify the iterator is not end(), then erase that iterator. Empty bags and absent values require no removal.

For k equal copies in n stored entries, count(x) and erase(x) may cost O(log(n + 1) + k). Repeatedly counting a huge equal run can become quadratic overall. Use contains for existence, or a frequency map when direct count queries are the main task.

Worked pattern: the ticket office

The rule is to serve customers in input order, selling the most expensive remaining ticket within each budget. upper_bound(budget) separates affordable prices from prices that are too large. Its guarded predecessor is the answer; erase that one iterator to preserve other equal-price tickets.

Before each customer, the multiset contains exactly the unsold tickets. This invariant explains both selection and removal. Building and processing q customers takes O((n + q)(1 + log(n + 1))) time and O(n) ticket storage.

C++23
// Complete C++23 program. Input: n q, n positive prices, q budgets.
#include <iostream>
#include <set>
int main() {
    int n, q;
    std::cin >> n >> q;
    std::multiset<int> prices;
    for (int i = 0; i < n; ++i) {
        int price;
        std::cin >> price;
        prices.insert(price);
    }
    while (q--) {
        int budget;
        std::cin >> budget;
        auto it = prices.upper_bound(budget);
        if (it == prices.begin()) std::cout << -1 << '\n';
        else {
            --it;
            std::cout << *it << '\n';
            prices.erase(it);
        }
    }
}

Set & multiset

Both containers keep values sorted. Erase one removes a single occurrence, like erase(iterator).

30
51
82

3 stored items · 3 distinct values

Guided simulation · Change the inputs to test your understanding.

Pause & predict

Tickets cost 4, 4, 9. Three customers each have budget 4. What should the outputs be?

Choose an answer
Try it yourself

Turn the idea into code

A multiset has 100000 copies of 5. Explain why calling count(5) once for every stored copy can be far slower than O(n log n).

Give me a hint

Count the matching entries visited by one count call, then count how many calls are made.

Show the explained solution

Each count may traverse all 100000 matching copies, and there are 100000 calls. That is O(n²) work. Store 5 → 100000 in a frequency map if the required operation is repeatedly reading the number of copies.

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.