Scheduling Unit Tasks with Deadlines and Penalties
A print shop has one press and a queue of jobs. Each job takes exactly one hour, each has a deadline, and each job finished after its deadline costs a penalty (a discount promised to the customer). Which jobs should run on time, and in what order, to minimise the total penalty? This is a real scheduling problem with possible orders, and the matroid greedy theorem solves it exactly in a few lines. The work is in recognising the matroid.
The problem
There are unit-time tasks . Task has an integer deadline with and a penalty . A schedule is an order of the tasks; the task in position (counting from 1) runs during hour and finishes at time . A task is late if it finishes after its deadline and early otherwise. Minimise the total penalty of the late tasks.
The running example, seven jobs:
| task | 1 | 2 | 3 | 4 | 5 | 6 | 7 |
|---|---|---|---|---|---|---|---|
| deadline | 3 | 1 | 4 | 2 | 3 | 4 | 6 |
| penalty | 25 | 35 | 40 | 15 | 30 | 20 | 10 |
Two simplifications
Early-first form. Any schedule can be rearranged so that all early tasks come before all late ones, without making any task late that was early: if a late task stands before an early one, swapping them moves the early task earlier (still early) and the late task later (still late).
Canonical form. Within the early tasks, sorting them by increasing deadline keeps them all early. (If two adjacent early tasks have with first, swapping them makes finish earlier and finish at the time used to, which is at most .)
So the problem is really about choosing which set of tasks will be early. Once is chosen, run it in deadline order, then the rest in any order. Minimising the penalty of the late tasks is the same as maximising the penalty of the early ones, . Call independent if some schedule has no late task among .
Lemma. For a set of tasks and , let be the number of tasks in with deadline at most . Then is independent if and only if for every .
Proof. If for some , more than tasks must finish by time , impossible. Conversely, if for all , run in deadline order: the task in position has at least tasks of with deadline at most its own deadline , namely itself and the ones before it, so , and it is early.
It is a matroid
Theorem. If is the set of tasks and the family of independent sets, then is a matroid.
Proof. Hereditary: removing tasks from can only decrease every . Exchange: let be independent with . Let be the largest with (take if there is none; for every set). Since , we have and for every . In particular has more tasks with deadline in than does, so some task has deadline greater than . Adding to raises by one only for , and there , because and is independent. For nothing changes. So is independent.
With the matroid established, the greedy theorem applies with the penalties as weights: consider the tasks in decreasing order of penalty and keep each one whose addition leaves the set independent. Tasks with penalty 0 can be dropped first, since the greedy theorem asks for positive weights and they never matter.
The algorithm
SCHEDULE(d, w) // tasks 1..n
1 A = empty set
2 for each task i in decreasing order of w[i]
3 if N_t(A + {i}) <= t for every t // the independence test of the lemma
4 A = A + {i}
5 return A in increasing order of deadline, then the remaining tasksfrom itertools import permutations
d = [3, 1, 4, 2, 3, 4, 6]
w = [25, 35, 40, 15, 30, 20, 10]
n = len(d)
def independent(A):
return all(sum(1 for i in A if d[i] <= t) <= t for t in range(1, n + 1))
A = []
for i in sorted(range(n), key=lambda i: -w[i]):
ok = independent(A + [i])
print(f"task {i + 1} (penalty {w[i]:2}, deadline {d[i]}): {'keep early' if ok else 'must be late'}")
if ok:
A.append(i)
early = sorted(A, key=lambda i: d[i])
late = [i for i in range(n) if i not in A]
schedule = early + late
print("schedule:", [i + 1 for i in schedule])
for hour, i in enumerate(schedule, 1):
print(f" hour {hour}: task {i + 1}, deadline {d[i]}" + (" LATE" if hour > d[i] else ""))
print("total penalty:", sum(w[i] for i in late))
best = min(sum(w[i] for t, i in enumerate(p, 1) if t > d[i]) for p in permutations(range(n)))
print("brute force over all", len(list(permutations(range(n)))), "schedules:", best)task 3 (penalty 40, deadline 4): keep early
task 2 (penalty 35, deadline 1): keep early
task 5 (penalty 30, deadline 3): keep early
task 1 (penalty 25, deadline 3): keep early
task 6 (penalty 20, deadline 4): must be late
task 4 (penalty 15, deadline 2): must be late
task 7 (penalty 10, deadline 6): keep early
schedule: [2, 5, 1, 3, 7, 4, 6]
hour 1: task 2, deadline 1
hour 2: task 5, deadline 3
hour 3: task 1, deadline 3
hour 4: task 3, deadline 4
hour 5: task 7, deadline 6
hour 6: task 4, deadline 2 LATE
hour 7: task 6, deadline 4 LATE
total penalty: 35
brute force over all 5040 schedules: 35
Task 6, with penalty 20 and deadline 4, is rejected because tasks 3, 2, 5 and 1 already use up all four hours before deadline 4: would become 5. Task 4 fails because of hour 2: tasks 2 and 4 both need one of the first two hours, but tasks 1 and 5 also need hours up to 3, and would exceed 3. The greedy schedule's penalty 35 matches brute force over all 5040 orders.
Other rules are not enough
Two tempting shortcuts ignore one of the two numbers: "earliest deadline first" (schedule by deadline and accept whatever ends up late) and "highest penalty first, in that order" (run the expensive tasks first, without the independence test). The program compares both with the matroid greedy and brute force on random instances.
import random
from itertools import permutations
def penalty(order, d, w):
return sum(w[i] for t, i in enumerate(order, 1) if t > d[i])
def matroid_greedy(d, w):
n, A = len(d), []
for i in sorted(range(n), key=lambda i: -w[i]):
if all(sum(1 for j in A + [i] if d[j] <= t) <= t for t in range(1, n + 1)):
A.append(i)
return sorted(A, key=lambda i: d[i]) + [i for i in range(n) if i not in A]
rules = {
"matroid greedy": matroid_greedy,
"earliest deadline first": lambda d, w: sorted(range(len(d)), key=lambda i: (d[i], -w[i])),
"highest penalty first": lambda d, w: sorted(range(len(d)), key=lambda i: -w[i]),
}
rng = random.Random(17)
wins = {name: 0 for name in rules}
example = {}
trials = 300
for _ in range(trials):
n = rng.randint(2, 6)
d = [rng.randint(1, n) for _ in range(n)]
w = [rng.randint(1, 50) for _ in range(n)]
best = min(penalty(p, d, w) for p in permutations(range(n)))
for name, rule in rules.items():
got = penalty(rule(d, w), d, w)
wins[name] += got == best
if got > best and name not in example:
example[name] = (d, w, got, best)
for name in rules:
print(f"{name:24}: optimal on {wins[name]}/{trials}")
for name, (d, w, got, best) in example.items():
print(f" {name} fails on deadlines {d}, penalties {w}: {got} instead of {best}")matroid greedy : optimal on 300/300
earliest deadline first : optimal on 220/300
highest penalty first : optimal on 108/300
earliest deadline first fails on deadlines [4, 3, 3, 3, 2, 6], penalties [46, 35, 43, 18, 8, 2]: 64 instead of 8
highest penalty first fails on deadlines [4, 3, 3, 3, 2, 6], penalties [46, 35, 43, 18, 8, 2]: 26 instead of 8
Only the matroid greedy is always optimal. Earliest deadline first wastes early slots on cheap tasks; highest penalty first runs an expensive task with a late deadline in a slot that a task with an early deadline needed.
Running time
With the independence test done by recomputing every , each test takes after an counting pass, so the algorithm runs in . A faster test assigns each accepted task to the latest free hour at or before its deadline; a task is independent of the current set exactly when such an hour exists. Finding "the latest free slot at or before " is a union-find query: each hour points to the next free hour to its left, and filling an hour unites it with its left neighbour. That brings the whole algorithm to for the sort plus nearly linear time for the slot queries (Disjoint-Set Operations).
In C++
The slot version with a small union-find structure. Slot 0 is a sentinel meaning "no free hour".
#include <algorithm>
#include <cstdio>
#include <numeric>
#include <vector>
int find(std::vector<int>& free_slot, int t) { // latest free hour <= t (0 = none)
return free_slot[t] == t ? t : free_slot[t] = find(free_slot, free_slot[t]);
}
int main() {
std::vector<int> d = {3, 1, 4, 2, 3, 4, 6}, w = {25, 35, 40, 15, 30, 20, 10};
int n = static_cast<int>(d.size());
std::vector<int> order(n), free_slot(n + 1), hour_of(n, 0);
std::iota(order.begin(), order.end(), 0);
std::stable_sort(order.begin(), order.end(), [&](int a, int b) { return w[a] > w[b]; });
std::iota(free_slot.begin(), free_slot.end(), 0);
int penalty = 0;
for (int i : order) {
int slot = find(free_slot, d[i]);
if (slot == 0) { penalty += w[i]; continue; } // no free hour before the deadline: late
hour_of[i] = slot;
free_slot[slot] = slot - 1; // the hour is taken; point left
}
std::printf("early tasks by hour:");
for (int t = 1; t <= n; ++t)
for (int i = 0; i < n; ++i)
if (hour_of[i] == t) std::printf(" [%d: task %d]", t, i + 1);
std::printf("\ntotal penalty %d\n", penalty);
}early tasks by hour: [1: task 2] [2: task 1] [3: task 5] [4: task 3] [6: task 7]
total penalty 35
The slots differ from the Python schedule (task 7 sits in hour 6 here, and some hours stay empty until the late tasks fill them), but the set of early tasks and the penalty are the same: any placement of an independent set can be turned into the canonical one. The same "latest free slot" greedy is the standard solution to the job-sequencing problem in programming contests, usually stated with profits instead of penalties.
Test yourself
Tasks with deadlines 1, 1, 2 (unit times). Is the set of all three independent?
- Yes
- No, because
- No, because
- Only if the penalties are equal
Why may we assume that the early tasks run in order of increasing deadline?
- Because greedy requires it
- Because swapping an adjacent pair that is out of deadline order never makes an early task late
- Because penalties are sorted
- Because all deadlines are distinct
In the matroid of independent task sets, what are the weights used by the greedy algorithm?
- The deadlines
- The penalties: maximising the penalty of the early tasks minimises that of the late ones
- The processing times
- One for every task