cppAcademy
FROM LEARNING TO COMPETING

Beginner.
Your first challenges.

Bulgarian Informatics Group E · 2007–2026

270 independently explained problems: 54 Municipal, 54 Regional, 105 National Olympiad tasks and 57 Autumn Tournament tasks. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group E also includes challenging national-level problems. Years follow Arena’s competition-season labels. Source clarifications are noted on affected tasks.
GROUP E2015 · EasySorting

Arrange Four Books

National Olympiad — Municipal round (2015 season)

Submission name: books.cpp

Problem summary

Arrange four books by decreasing height. Among books of equal height, put thicker books first. All four thicknesses differ.

Input

Four lines, each with height h and thickness th.

Output

Four lines with the same height-thickness pairs in the required order.

Constraints

1 ≤ h, th ≤ 1000.

Worked example

An independently prepared example for this explanation.

Input

2 23
7 150
7 100
22 37

Output

22 37
7 150
7 100
2 23

Solution analysis

  1. A book must keep its own height and thickness together, so store each book as a pair rather than sorting the two measurements separately.
  2. Pairs are compared lexicographically: first height, then thickness. Sorting pairs in descending order implements exactly the two requested priorities.
  3. In the example height 22 comes first and height 2 last. The two height-7 books go in thickness order 150, then 100.

Why it works

Descending lexicographic order places every larger height earlier; when heights tie, it places the larger thickness earlier. These are exactly the arrangement rules, and sorting preserves each original book pair.

Complexity: O(4 log 4) time and O(4) space; both constant.

Watch out. Do not sort height and thickness independently. Both sorting keys are decreasing.

Commented C++17 solution

An independently written complete program with standard headers.

#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    vector<pair<int, int>> books(4);
    for (auto &book : books) {
        cin >> book.first >> book.second;
    }
    // Descending pair order compares height before thickness.
    sort(books.rbegin(), books.rend());
    for (const auto &book : books) {
        cout << book.first << ' ' << book.second << '\n';
    }
    return 0;
}

Source: Arena Olimpiici ↗