TExcelTAD
Home › Design Techniques: Dynamic Programming, Greedy & Amortized Analysis › Scheduling Unit Tasks with Deadlines and Penalties

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 n!n! 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 nn unit-time tasks a1,…,ana_1, \ldots, a_n. Task aia_i has an integer deadline did_i with 1≤di≤n1 \le d_i \le n and a penalty wi≥0w_i \ge 0. A schedule is an order of the tasks; the task in position tt (counting from 1) runs during hour tt and finishes at time tt. 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 did_i 3 1 4 2 3 4 6
penalty wiw_i 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 di>djd_i > d_j with aia_i first, swapping them makes aja_j finish earlier and aia_i finish at the time aja_j used to, which is at most dj<did_j < d_i.)

So the problem is really about choosing which set AA of tasks will be early. Once AA 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, w(A)w(A). Call AA independent if some schedule has no late task among AA.

Lemma. For a set AA of tasks and t=1,…,nt = 1, \ldots, n, let Nt(A)N_t(A) be the number of tasks in AA with deadline at most tt. Then AA is independent if and only if Nt(A)≤tN_t(A) \le t for every tt.

Proof. If Nt(A)>tN_t(A) > t for some tt, more than tt tasks must finish by time tt, impossible. Conversely, if Nt(A)≤tN_t(A) \le t for all tt, run AA in deadline order: the task in position kk has at least kk tasks of AA with deadline at most its own deadline dd, namely itself and the ones before it, so k≤Nd(A)≤dk \le N_d(A) \le d, and it is early. ■\blacksquare

It is a matroid

Theorem. If SS is the set of tasks and I\mathcal{I} the family of independent sets, then (S,I)(S, \mathcal{I}) is a matroid.

Proof. Hereditary: removing tasks from AA can only decrease every NtN_t. Exchange: let A,BA, B be independent with ∣A∣<∣B∣\lvert A \rvert < \lvert B \rvert. Let kk be the largest tt with Nt(B)≤Nt(A)N_t(B) \le N_t(A) (take k=0k = 0 if there is none; N0=0N_0 = 0 for every set). Since Nn(B)=∣B∣>∣A∣=Nn(A)N_n(B) = \lvert B \rvert > \lvert A \rvert = N_n(A), we have k<nk < n and Nj(B)>Nj(A)N_j(B) > N_j(A) for every j>kj > k. In particular BB has more tasks with deadline in k+1..nk + 1..n than AA does, so some task x∈B∖Ax \in B \setminus A has deadline greater than kk. Adding xx to AA raises NjN_j by one only for j≥dx>kj \ge d_x > k, and there Nj(A)+1≤Nj(B)≤jN_j(A) + 1 \le N_j(B) \le j, because Nj(A)<Nj(B)N_j(A) < N_j(B) and BB is independent. For j<dxj < d_x nothing changes. So A∪{x}A \cup \{x\} is independent. ■\blacksquare

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

text
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 tasks
python · try it yourself
from 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: N4N_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 N3N_3 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.

python · try it yourself
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 NtN_t, each test takes O(n)O(n) after an O(n)O(n) counting pass, so the algorithm runs in O(n2)O(n^2). 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 dd" 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 O(nlg⁡n)O(n \lg n) 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".

cpp · try it yourself
#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?

  1. Yes
  2. No, because N1=2>1N_1 = 2 > 1
  3. No, because N2=2>1N_2 = 2 > 1
  4. Only if the penalties are equal

Why may we assume that the early tasks run in order of increasing deadline?

  1. Because greedy requires it
  2. Because swapping an adjacent pair that is out of deadline order never makes an early task late
  3. Because penalties are sorted
  4. Because all deadlines are distinct

In the matroid of independent task sets, what are the weights used by the greedy algorithm?

  1. The deadlines
  2. The penalties: maximising the penalty of the early tasks minimises that of the late ones
  3. The processing times
  4. One for every task