Four contest problems rated 1,200 to 1,400 where the sort is the first move, not the answer. The move: sort once by the right key, so every later decision looks at one end, one neighbour or one sum.
This tent holds four problems rated 1,200 to 1,400. In each one the sort is the first move and not the answer. Once the data is sorted, every decision looks at one end of the list, at a neighbour, or at a running maximum.
| Problem | Sorted by | What the order gives |
|---|---|---|
| Shelf order by price band then rating | band, then rating high first, then item number | the order is the answer |
| Widest pairings of server loads | the readings | the best pairs use the two ends |
| Offline map regions along a route | the first kilometre of each region | the next candidates are the next regions in the list |
| How out of order is the playlist | the scores, inside a merge sort | a right value leaving sees every waiting left value as larger |
The first row looks easy, and its trap is a tie. Two items can share a band and a rating, and the statement then says to show the lower item number first. A C++ std::sort does not promise to keep equal keys in their original order, so you must put the item number last in the key. Then no two keys are equal and every language gives the same order.
Sort the item numbers instead of the values when the answer names items. Choose the key so that the choice after the sort is easy, and end it with the item number.
After the sort, every decision should look at one end, one neighbour or one running maximum. If it needs to search the whole list, the key is wrong.
The widest pairings show the idea. Take the readings 5, 1, 9 and 4 with k = 2, which sort to 1, 4, 5, 9. The two highest are 5 and 9, the two lowest are 1 and 4, and the best total gap is (9 + 5) - (1 + 4) = 9. Any pairing of the two highest with the two lowest gives the same total, so no pairing is built.
Exercise · Put it in order: The k widest pairings. Arrange the lines into a function that returns the largest total gap of k disjoint pairs. Sort first, then add the k lowest and the k highest values.
def best_spread(readings, k):
ordered = sorted(readings)
high = 0
low = 0
for i in range(k):
low += ordered[i]
high += ordered[len(ordered) - 1 - i]
return high - low
high += ordered[len(ordered) - i]The map regions use the sort in a different way. Sort the regions by their first kilometre, and the next region to take is always among those that start at or before the first uncovered kilometre. That first uncovered kilometre is one past the covered end, because a region ending at 5 and one starting at 6 leave no gap. Among those candidates, take the one that reaches furthest.
Exercise · Predict the output: How the covered end moves. Five regions are sorted by their first kilometre. This covers the kilometres 1 to 10 and prints the covered end after each region taken. What does it print?
starts = [1, 2, 4, 6, 7]
ends = [3, 5, 8, 7, 10]
covered = 0
i = 0
while covered < 10:
reach = covered
while i < len(starts) and starts[i] <= covered + 1:
reach = max(reach, ends[i])
i += 1
covered = reach
print(covered)Exercise · Find the bug: The wrong sort key. This returns the fewest regions that cover the kilometres 1 to length, or -1. It sorts the region numbers before it scans them. Which line is wrong?
def fewest_regions(starts, ends, length):
n = len(starts)
order = sorted(range(n), key=lambda i: ends[i])
covered = 0
count = 0
i = 0
while covered < length:
reach = covered
while i < n and starts[order[i]] <= covered + 1:
reach = max(reach, ends[order[i]])
i += 1
if reach == covered:
return -1
covered = reach
count += 1
return countThe playlist problem adds a sum to a merge sort. In the merge, a right value leaves while waiting left values remain. All of them are larger, because the left half is sorted, and together their gaps are waiting_sum - waiting × value.
Take the scores 3, 1 and 2, with the left half 3 and the right half 1 and 2. The value 1 adds 3 - 1 = 2 and the value 2 adds 3 - 2 = 1, which gives a total disorder of 3.
Sort regions by start; among those starting next to the covered end, take the one that reaches furthest.
The Academy lessons Comparators, Merge sort and inversions and Intervals taught the tools, and Greedy by sorting taught when to sort. A contest uses them with fewer hints, so three habits change.
First, you sort an index list and end the key with the index, which fixes every tie. Second, a sort can replace a search: after it, a hard choice of pairs is arithmetic on two ends. Third, a merge sort can carry a sum, so a weighted count stays in O(n log n) time.
The third change has a tempting shortcut. Sum the gaps of neighbouring pairs only, and a list that is nearly in order looks fine. For the scores 3, 2 and 1 the neighbours give 1 + 1 = 2, while all three pairs give 1 + 2 + 1 = 4.
A sum over neighbouring pairs misses pairs that are far apart; all pairs of 3, 2 and 1 give 4, not 2.
Exercise · Break it: The playlist that counts only neighbours. A pair of positions i < j is out of order when its earlier score is larger, and its disorder is the difference. This adds the disorder of neighbouring pairs only. Find an input where it is wrong.
def total_disorder(scores):
total = 0
for i in range(len(scores) - 1):
if scores[i] > scores[i + 1]:
total += scores[i] - scores[i + 1]
return total| Limit | What it tells you |
|---|---|
| 10^5 items with keys up to 10^6 | one sort of the item numbers, O(n log n) |
| readings up to 10^9 and k up to 50,000 | the two sums reach 5 × 10^13: use 64 bits |
| 10^5 regions on a route of up to 10^6 kilometres | one sort, then a pointer that never moves back |
| 10^5 scores up to 10^6 | a total gap of up to 2.5 × 10^15, so 64 bits |
The last bound comes from half the scores at 10^6 placed before half at 0. That is 50,000 × 50,000 = 2.5 × 10^9 pairs of gap 10^6 each.
The full treatment is in Fast I/O and stress testing. Here the output is one line of item numbers, so build it once and print once.
import sys
def main():
data = sys.stdin.buffer.read().split()
n = int(data[0])
band = int(data[1])
prices = list(map(int, data[2:2 + n]))
ratings = list(map(int, data[2 + n:2 + 2 * n]))
order = sorted(range(n), key=lambda i: (prices[i] // band, -ratings[i], i))
sys.stdout.write(" ".join(map(str, order)) + "\n")
main()import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) throws IOException {
StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
in.nextToken();
int n = (int) in.nval;
in.nextToken();
int band = (int) in.nval;
int[] prices = new int[n];
int[] ratings = new int[n];
for (int i = 0; i < n; i++) { in.nextToken(); prices[i] = (int) in.nval; }
for (int i = 0; i < n; i++) { in.nextToken(); ratings[i] = (int) in.nval; }
Integer[] order = new Integer[n];
for (int i = 0; i < n; i++) order[i] = i;
Arrays.sort(order, (a, b) -> {
if (prices[a] / band != prices[b] / band) return Integer.compare(prices[a] / band, prices[b] / band);
if (ratings[a] != ratings[b]) return Integer.compare(ratings[b], ratings[a]);
return Integer.compare(a, b);
});
StringBuilder out = new StringBuilder();
for (int i = 0; i < n; i++) out.append(i > 0 ? " " : "").append(order[i]);
System.out.println(out);
}
}#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, band;
cin >> n >> band;
vector<int> prices(n), ratings(n);
for (auto& x : prices) cin >> x;
for (auto& x : ratings) cin >> x;
vector<int> order(n);
iota(order.begin(), order.end(), 0);
sort(order.begin(), order.end(), [&](int a, int b) {
if (prices[a] / band != prices[b] / band) return prices[a] / band < prices[b] / band;
if (ratings[a] != ratings[b]) return ratings[a] > ratings[b];
return a < b;
});
for (int i = 0; i < n; i++) cout << order[i] << (i + 1 < n ? " " : "\n");
}const data = require("fs").readFileSync(0, "utf8").split(/\s+/).filter(Boolean).map(Number);
const n = data[0];
const band = data[1];
const prices = data.slice(2, 2 + n);
const ratings = data.slice(2 + n, 2 + 2 * n);
const order = prices.map((_, i) => i);
order.sort((a, b) => {
const bandA = Math.floor(prices[a] / band);
const bandB = Math.floor(prices[b] / band);
if (bandA !== bandB) return bandA - bandB;
if (ratings[a] !== ratings[b]) return ratings[b] - ratings[a];
return a - b;
});
process.stdout.write(order.join(" ") + "\n");On the sample of 4 items with the band 10, the prices 30, 12, 18, 25 and the ratings 4, 5, 5, 3, all four programs print 1 2 3 0.
The slow twin of the playlist problem tries every pair of positions. The generator draws short lists of small scores, which makes ties and equal runs common.
import random
from fast import total_disorder
from slow import total_disorder as slow_disorder
for seed in range(1000):
rng = random.Random(seed)
scores = [rng.randint(0, 20) for _ in range(rng.randint(1, 12))]
if total_disorder(scores) != slow_disorder(scores):
print("different at", scores)
break
else:
print("all 1000 inputs agree")The run prints all 1000 inputs agree. Now swap in the neighbours-only sum. The first seed already fails, with the scores 13, 1, 8, 16, 15, 12 and 9. The shortcut gives 19 and the pairs give 46.
At this band the sort and the scan are short, and the work is choosing the key. Before you code, write the key in one line and say what the first element of the sorted list means. Aim for about 20 minutes a problem.
The first is the sort itself, with a key that has three parts. The second turns a search for pairs into two sums. The third scans the sorted regions with a pointer, and the last carries a sum through a merge.
For each problem, write the sort key in one line, then the one fact about the sorted list that makes the next choice local. Build the slow twin before you write the fast code.
Checkpoint · Sorting tricks
Q1/5 The readings are 5, 1, 9 and 4, and k is 2. What is the largest total gap of 2 disjoint pairs?
Answer: B
Sorted, the readings are 1, 4, 5, 9. The two highest add up to 14 and the two lowest to 5, so the best total is 14 - 5 = 9. A total of 14 forgets to subtract the lowest.
Q2/5 Why does the key for the shelf order end with the item number?
Answer: B
The statement shows the lower item number first on a tie. A key without it leaves ties undecided, and a C++ sort does not keep equal keys in their original order.
Q3/5 The covered end is 5 and a region starts at 6. Can it be the next region?
Answer: B
Kilometre 6 is the first uncovered one, so a region that starts at 6 is a candidate. The test is a start of at most the covered end plus 1.
Q4/5 The scores are 3, 2 and 1. What is the total disorder of all pairs?
Answer: C
The pairs give 1 + 2 + 1 = 4. Neighbouring pairs alone give 2, which misses the pair 3 and 1.
Q5/5 In a merge, a right value 4 leaves while the left values 5 and 6 still wait. What does it add to the total disorder?
Answer: B
Both waiting values are larger than 4. Their gaps are 1 and 2, which is the sum 11 minus 2 × 4 = 3.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.