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
- A book must keep its own height and thickness together, so store each book as a pair rather than sorting the two measurements separately.
- Pairs are compared lexicographically: first height, then thickness. Sorting pairs in descending order implements exactly the two requested priorities.
- 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.
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;
}