TExcelTAD
Home › Linear Programming & Duality for Algorithms › Mini Project: An Assignment Solver with a Dual Certificate

Mini Project: An Assignment Solver with a Dual Certificate

An optimization result is only as trustworthy as the evidence that comes with it. In this project you build a small assignment solver that returns, together with each optimal assignment, a dual certificate: vertex potentials that prove no other assignment is cheaper. A separate checker verifies the certificate in exact arithmetic, using only weak duality and complementary slackness, so it never has to trust the solver. Then the same machinery schedules jobs on two unrelated machines to minimize the total completion time, a scheduling problem that turns out to be an assignment problem in disguise.

The steps:

  1. Model the assignment problem as an LP and solve it with SciPy.
  2. Write the certificate checker and apply it to SciPy's dual values.
  3. Implement the Hungarian method, a primal-dual algorithm that produces the certificate itself, and check that a tampered certificate is rejected.
  4. Turn a scheduling problem into an assignment problem and certify the schedule.
  5. Use reduced costs to answer "what if" questions.
  6. Port the solver and checker to C++.

Each step is a complete program; later steps repeat the pieces they need.

Step 1: The LP model

Four workers, four jobs, cost cijc_{ij} for worker ii doing job jj; each worker does one job and each job is done once. The LP is

min⁡∑i,jcijxijs.t.∑jxij=1 ∀i,∑ixij=1 ∀j,x≥0.\min \sum_{i,j} c_{ij} x_{ij} \quad \text{s.t.} \quad \sum_j x_{ij} = 1 \ \forall i, \quad \sum_i x_{ij} = 1 \ \forall j, \quad x \ge 0 .

Its matrix is the incidence matrix of the complete bipartite graph, which is totally unimodular (Bipartite, Network and Interval Matrices), so a vertex solution is a permutation matrix and the LP solves the integer problem.

python · try it yourself
from scipy.optimize import linprog

C = [[8, 4, 7, 3], [5, 9, 6, 4], [6, 7, 3, 8], [4, 6, 9, 5]]
n = len(C)
var = [(i, j) for i in range(n) for j in range(n)]
A_eq = [[1 if v[0] == i else 0 for v in var] for i in range(n)] + [[1 if v[1] == j else 0 for v in var] for j in range(n)]
res = linprog([C[i][j] for i, j in var], A_eq=A_eq, b_eq=[1] * (2 * n), bounds=[(0, None)] * len(var), method="highs-ds")
assignment = {i: j for (i, j), x in zip(var, res.x) if x > 0.5}
print("status:", "optimal" if res.status == 0 else res.status)
print("assignment (worker -> job):", assignment)
print("cost:", round(float(res.fun), 6), "=", " + ".join(str(C[i][j]) for i, j in assignment.items()))
print("all x are 0 or 1:", all(abs(x) < 1e-9 or abs(x - 1) < 1e-9 for x in res.x))
status: optimal
assignment (worker -> job): {0: 1, 1: 3, 2: 2, 3: 0}
cost: 15.0 = 4 + 4 + 3 + 4
all x are 0 or 1: True

Step 2: The certificate checker

The dual of the assignment LP has a free variable per equation, uiu_i for worker ii and vjv_j for job jj:

max⁡∑iui+∑jvjs.t.ui+vj≤cij  ∀i,j.\max \sum_i u_i + \sum_j v_j \quad \text{s.t.} \quad u_i + v_j \le c_{ij} \ \ \forall i, j .

A permutation π\pi and potentials (u,v)(u, v) certify each other when (1) π\pi is a permutation, (2) ui+vj≤ciju_i + v_j \le c_{ij} everywhere, and (3) every assigned pair is tight, ui+vπ(i)=ciπ(i)u_i + v_{\pi(i)} = c_{i \pi(i)}, which is complementary slackness. Then the cost equals the dual value, and by weak duality no assignment, fractional or integral, is cheaper. The checker uses Fraction throughout, and the program feeds it SciPy's dual values (eqlin.marginals), converted to rationals.

python · try it yourself
from fractions import Fraction as F
from scipy.optimize import linprog

def check_certificate(C, perm, u, v):
    n = len(C)
    u, v = [F(x) for x in u], [F(x) for x in v]
    report = {
        "perm is a permutation": sorted(perm) == list(range(n)),
        "dual feasible: u_i + v_j <= c_ij": all(u[i] + v[j] <= C[i][j] for i in range(n) for j in range(n)),
        "complementary slackness on assigned pairs": all(u[i] + v[perm[i]] == C[i][perm[i]] for i in range(n)),
    }
    primal, dual = sum(C[i][perm[i]] for i in range(n)), sum(u) + sum(v)
    report["primal cost = dual value"] = primal == dual
    return all(report.values()), report, primal, dual

C = [[8, 4, 7, 3], [5, 9, 6, 4], [6, 7, 3, 8], [4, 6, 9, 5]]
n = len(C)
var = [(i, j) for i in range(n) for j in range(n)]
A_eq = [[1 if w[0] == i else 0 for w in var] for i in range(n)] + [[1 if w[1] == j else 0 for w in var] for j in range(n)]
res = linprog([C[i][j] for i, j in var], A_eq=A_eq, b_eq=[1] * (2 * n), bounds=[(0, None)] * len(var), method="highs-ds")
perm = [next(j for j in range(n) if res.x[i * n + j] > 0.5) for i in range(n)]
y = [F(float(m)).limit_denominator(1000) for m in res.eqlin.marginals]
ok, report, primal, dual = check_certificate(C, perm, y[:n], y[n:])
for k, v in report.items():
    print(f"  {k:44} {v}")
print("certified optimal:", ok, " cost", primal, " dual value", dual)
  perm is a permutation                        True
  dual feasible: u_i + v_j <= c_ij             True
  complementary slackness on assigned pairs    True
  primal cost = dual value                     True
certified optimal: True  cost 15  dual value 15

The potentials themselves are not unique (the assignment LP is degenerate, and many duals are optimal), which is why the program prints only the checks. Any optimal dual passes.

Step 3: The Hungarian method

A solver that produces its own certificate needs no LP library. The Hungarian method (Kuhn, 1955, building on König and Egerváry; this O(n3)O(n^3) version follows the standard shortest-augmenting-path formulation) is a primal-dual algorithm: it keeps feasible potentials, grows a matching using only tight edges, and when it is stuck it changes the potentials by the smallest amount that makes a new edge tight. When the matching is perfect, the potentials are exactly the certificate of Step 2.

text
HUNGARIAN(C)                                   -- n x n integer costs
1  u = 0, v = 0, no row matched
2  for each row i:  grow a tree of alternating paths from i, using reduced costs c_ij - u_i - v_j
3      repeat: let delta = the smallest reduced cost from the tree to a column outside it
4              raise u on tree rows and lower v on tree columns by delta   -- keeps u_i + v_j <= c_ij
5              add the newly tight column; stop when it is unmatched
6      augment along the tree path to that column                       -- matching grows by one
7  return the matching and (u, v)

The program runs it on the same costs, checks the certificate, and then tampers with it twice: lowering the cost claim by changing one potential, and swapping two jobs in the assignment. The checker rejects both.

python · try it yourself
from fractions import Fraction as F

def hungarian(C):
    """Min-cost perfect assignment. Returns (perm, u, v) with u_i + v_j <= C[i][j], tight on perm."""
    n = len(C)
    INF = float("inf")
    u, v = [0] * (n + 1), [0] * (n + 1)          # 1-based; index 0 is an auxiliary column
    match_col = [0] * (n + 1)                    # match_col[j] = row matched to column j
    way = [0] * (n + 1)
    for i in range(1, n + 1):
        match_col[0], j0 = i, 0
        minv, used = [INF] * (n + 1), [False] * (n + 1)
        while True:
            used[j0] = True
            i0, delta, j1 = match_col[j0], INF, 0
            for j in range(1, n + 1):
                if not used[j]:
                    cur = C[i0 - 1][j - 1] - u[i0] - v[j]
                    if cur < minv[j]:
                        minv[j], way[j] = cur, j0
                    if minv[j] < delta:
                        delta, j1 = minv[j], j
            for j in range(n + 1):
                if used[j]:
                    u[match_col[j]] += delta
                    v[j] -= delta
                else:
                    minv[j] -= delta
            j0 = j1
            if match_col[j0] == 0:
                break
        while j0:                                # augment along the alternating path
            j1 = way[j0]
            match_col[j0] = match_col[j1]
            j0 = j1
    perm = [0] * n
    for j in range(1, n + 1):
        perm[match_col[j] - 1] = j - 1
    return perm, u[1:], v[1:]

def check_certificate(C, perm, u, v):
    n = len(C)
    u, v = [F(x) for x in u], [F(x) for x in v]
    ok = (sorted(perm) == list(range(n))
          and all(u[i] + v[j] <= C[i][j] for i in range(n) for j in range(n))
          and all(u[i] + v[perm[i]] == C[i][perm[i]] for i in range(n)))
    return ok, sum(C[i][perm[i]] for i in range(n)), str(sum(u) + sum(v))

C = [[8, 4, 7, 3], [5, 9, 6, 4], [6, 7, 3, 8], [4, 6, 9, 5]]
perm, u, v = hungarian(C)
print("assignment:", {i: perm[i] for i in range(len(C))}, " u =", u, " v =", v)
print("certificate (ok, cost, dual value):", check_certificate(C, perm, u, v))

bad_u = u[:]
bad_u[0] += 1                                    # claims a dual value one higher
print("tampered potential:", check_certificate(C, perm, bad_u, v))
bad_perm = perm[:]
bad_perm[0], bad_perm[1] = bad_perm[1], bad_perm[0]
print("tampered assignment:", check_certificate(C, bad_perm, u, v))
assignment: {0: 1, 1: 3, 2: 2, 3: 0}  u = [4, 5, 3, 4]  v = [0, 0, 0, -1]
certificate (ok, cost, dual value): (True, 15, '15')
tampered potential: (False, 15, '16')
tampered assignment: (False, 19, '15')

Raising u0u_0 breaks dual feasibility on worker 0's tight edge, and swapping two jobs breaks complementary slackness. In both cases the checker answers "not certified" even though the claimed values look plausible.

Step 4: A scheduler in disguise

Five jobs must run on two machines. Job jj takes p1jp_{1j} time units on machine 1 and p2jp_{2j} on machine 2 (the machines are unrelated: neither is uniformly faster). Each machine runs its jobs one after another from time 0. Minimize the sum of completion times ∑jCj\sum_j C_j.

The trick (Horn, 1973; Bruno, Coffman and Sethi, 1974): if a job is the kk-th from last on machine ii, its processing time is counted in the completion time of itself and of the k−1k - 1 jobs after it, so it contributes exactly k⋅pijk \cdot p_{ij} to the total. So assign jobs to slots (i,k)(i, k), each slot used at most once, with cost k⋅pijk \cdot p_{ij}: a rectangular assignment problem, 55 jobs by 2⋅5=102 \cdot 5 = 10 slots. Pad it with 5 dummy jobs of cost 0 to make it square. (An optimal solution always fills positions 1,2,…1, 2, \ldots without gaps, because moving a job into an empty lower position reduces its multiplier.)

python · try it yourself
from fractions import Fraction as F
from itertools import product

def hungarian(C):
    n = len(C)
    INF = float("inf")
    u, v, match_col, way = [0] * (n + 1), [0] * (n + 1), [0] * (n + 1), [0] * (n + 1)
    for i in range(1, n + 1):
        match_col[0], j0 = i, 0
        minv, used = [INF] * (n + 1), [False] * (n + 1)
        while True:
            used[j0] = True
            i0, delta, j1 = match_col[j0], INF, 0
            for j in range(1, n + 1):
                if not used[j]:
                    cur = C[i0 - 1][j - 1] - u[i0] - v[j]
                    if cur < minv[j]:
                        minv[j], way[j] = cur, j0
                    if minv[j] < delta:
                        delta, j1 = minv[j], j
            for j in range(n + 1):
                if used[j]:
                    u[match_col[j]] += delta; v[j] -= delta
                else:
                    minv[j] -= delta
            j0 = j1
            if match_col[j0] == 0:
                break
        while j0:
            j1 = way[j0]; match_col[j0] = match_col[j1]; j0 = j1
    perm = [0] * n
    for j in range(1, n + 1):
        perm[match_col[j] - 1] = j - 1
    return perm, u[1:], v[1:]

def certified(C, perm, u, v):
    n = len(C)
    return (sorted(perm) == list(range(n)) and all(u[i] + v[j] <= C[i][j] for i in range(n) for j in range(n))
            and all(u[i] + v[perm[i]] == C[i][perm[i]] for i in range(n)))

p = [[3, 7, 2, 6, 4], [5, 4, 6, 2, 8]]              # p[machine][job]
jobs, machines = 5, 2
slots = [(i, k) for i in range(machines) for k in range(1, jobs + 1)]   # k = position from the end
C = [[k * p[i][j] for (i, k) in slots] for j in range(jobs)] + [[0] * len(slots) for _ in range(len(slots) - jobs)]
perm, u, v = hungarian(C)
print("certificate valid:", certified(C, perm, u, v), " total completion time:", sum(C[j][perm[j]] for j in range(jobs)))

for i in range(machines):
    mine = sorted((slots[perm[j]][1], j) for j in range(jobs) if slots[perm[j]][0] == i)
    order = [j for _, j in sorted(mine, reverse=True)]                 # largest k runs first
    t, timeline = 0, []
    for j in order:
        t += p[i][j]
        timeline.append(f"job {j} ends at {t}")
    print(f"machine {i + 1}: " + ", ".join(timeline))

def total_spt(assign):                            # brute force: each machine runs its jobs shortest first
    total = 0
    for i in range(machines):
        t = 0
        for d in sorted(p[i][j] for j in range(jobs) if assign[j] == i):
            t += d
            total += t
    return total
print("brute force over all 2^5 machine assignments:", min(total_spt(a) for a in product(range(machines), repeat=jobs)))
certificate valid: True  total completion time: 24
machine 1: job 2 ends at 2, job 0 ends at 5, job 4 ends at 9
machine 2: job 3 ends at 2, job 1 ends at 6
brute force over all 2^5 machine assignments: 24

The certified assignment schedule and the brute-force optimum agree. On each machine the jobs end up in shortest processing time first order, as they must: a larger multiplier kk belongs to a shorter job. The brute force needs 2n2^n machine assignments; the assignment formulation is polynomial for any number of jobs and machines.

Step 5: Reduced costs answer "what if"

For a pair (i,j)(i, j) not in the assignment, the reduced cost cˉij=cij−ui−vj≥0\bar c_{ij} = c_{ij} - u_i - v_j \ge 0 is a safety margin: as long as cijc_{ij} stays at least ui+vju_i + v_j, the same potentials still certify the same assignment, because the checker's conditions involve that entry only through ui+vj≤ciju_i + v_j \le c_{ij}. The program lists the reduced costs and then lowers one entry step by step.

python · try it yourself
def hungarian(C):
    n = len(C)
    INF = float("inf")
    u, v, match_col, way = [0] * (n + 1), [0] * (n + 1), [0] * (n + 1), [0] * (n + 1)
    for i in range(1, n + 1):
        match_col[0], j0 = i, 0
        minv, used = [INF] * (n + 1), [False] * (n + 1)
        while True:
            used[j0] = True
            i0, delta, j1 = match_col[j0], INF, 0
            for j in range(1, n + 1):
                if not used[j]:
                    cur = C[i0 - 1][j - 1] - u[i0] - v[j]
                    if cur < minv[j]:
                        minv[j], way[j] = cur, j0
                    if minv[j] < delta:
                        delta, j1 = minv[j], j
            for j in range(n + 1):
                if used[j]:
                    u[match_col[j]] += delta; v[j] -= delta
                else:
                    minv[j] -= delta
            j0 = j1
            if match_col[j0] == 0:
                break
        while j0:
            j1 = way[j0]; match_col[j0] = match_col[j1]; j0 = j1
    perm = [0] * n
    for j in range(1, n + 1):
        perm[match_col[j] - 1] = j - 1
    return perm, u[1:], v[1:]

C = [[8, 4, 7, 3], [5, 9, 6, 4], [6, 7, 3, 8], [4, 6, 9, 5]]
perm, u, v = hungarian(C)
print("reduced costs c_ij - u_i - v_j (0 on assigned pairs, marked *):")
for i in range(4):
    print("  worker", i, " ".join(f"{C[i][j] - u[i] - v[j]:3}{'*' if perm[i] == j else ' '}" for j in range(4)))

i, j = 2, 0                                        # worker 2 on job 0: how cheap must it get?
print(f"reduced cost of worker {i} on job {j}: {C[i][j] - u[i] - v[j]}")
for new in [6, 4, 3, 2, 0, -1]:
    C2 = [row[:] for row in C]
    C2[i][j] = new
    old_still_valid = all(u[a] + v[b] <= C2[a][b] for a in range(4) for b in range(4))
    perm2, _, _ = hungarian(C2)
    print(f"c[{i}][{j}] = {new:2}: old certificate valid {str(old_still_valid):5}, "
          f"optimal cost {sum(C2[a][perm2[a]] for a in range(4)):2}, worker {i} gets job {perm2[i]}")
reduced costs c_ij - u_i - v_j (0 on assigned pairs, marked *):
  worker 0   4    0*   3    0
  worker 1   0    4    1    0*
  worker 2   3    4    0*   6
  worker 3   0*   2    5    2
reduced cost of worker 2 on job 0: 3
c[2][0] =  6: old certificate valid True , optimal cost 15, worker 2 gets job 2
c[2][0] =  4: old certificate valid True , optimal cost 15, worker 2 gets job 2
c[2][0] =  3: old certificate valid True , optimal cost 15, worker 2 gets job 2
c[2][0] =  2: old certificate valid False, optimal cost 15, worker 2 gets job 2
c[2][0] =  0: old certificate valid False, optimal cost 15, worker 2 gets job 2
c[2][0] = -1: old certificate valid False, optimal cost 14, worker 2 gets job 0

Worker 2 on job 0 has reduced cost 3, so the old potentials keep certifying the old assignment while c20≥3c_{20} \ge 3. Below that the old certificate breaks, yet the assignment stays optimal down to c20=0c_{20} = 0 and changes only at c20=−1c_{20} = -1: the cheapest assignment that uses the pair costs c20+15c_{20} + 15, so it wins only when c20<0c_{20} < 0. The reduced cost is a guaranteed safety margin read straight off the certificate; the exact breakpoint needs a re-optimization (here, the best assignment with the pair forced in). Reduced costs are the combinatorial version of the shadow prices of an LP, with the same caveat: they are local information.

Step 6: In C++

The Hungarian method and the certificate check in C++20 with long long costs, on the assignment instance of Step 1.

cpp · try it yourself
#include <cstdio>
#include <limits>
#include <vector>

using Mat = std::vector<std::vector<long long>>;

// Min-cost assignment; fills perm (row -> column) and potentials u, v with u_i + v_j <= C_ij.
void hungarian(const Mat& C, std::vector<int>& perm, std::vector<long long>& u, std::vector<long long>& v) {
    int n = C.size();
    const long long INF = std::numeric_limits<long long>::max() / 4;
    std::vector<long long> U(n + 1, 0), V(n + 1, 0);
    std::vector<int> matchCol(n + 1, 0), way(n + 1, 0);
    for (int i = 1; i <= n; i++) {
        matchCol[0] = i;
        int j0 = 0;
        std::vector<long long> minv(n + 1, INF);
        std::vector<bool> used(n + 1, false);
        do {
            used[j0] = true;
            int i0 = matchCol[j0], j1 = 0;
            long long delta = INF;
            for (int j = 1; j <= n; j++)
                if (!used[j]) {
                    long long cur = C[i0 - 1][j - 1] - U[i0] - V[j];
                    if (cur < minv[j]) { minv[j] = cur; way[j] = j0; }
                    if (minv[j] < delta) { delta = minv[j]; j1 = j; }
                }
            for (int j = 0; j <= n; j++)
                if (used[j]) { U[matchCol[j]] += delta; V[j] -= delta; } else minv[j] -= delta;
            j0 = j1;
        } while (matchCol[j0] != 0);
        do { int j1 = way[j0]; matchCol[j0] = matchCol[j1]; j0 = j1; } while (j0);
    }
    perm.assign(n, 0);
    for (int j = 1; j <= n; j++) perm[matchCol[j] - 1] = j - 1;
    u.assign(U.begin() + 1, U.end());
    v.assign(V.begin() + 1, V.end());
}

bool certified(const Mat& C, const std::vector<int>& perm, const std::vector<long long>& u, const std::vector<long long>& v) {
    int n = C.size();
    std::vector<bool> seen(n, false);
    for (int j : perm) { if (seen[j]) return false; seen[j] = true; }
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++) if (u[i] + v[j] > C[i][j]) return false;     // dual feasibility
    for (int i = 0; i < n; i++) if (u[i] + v[perm[i]] != C[i][perm[i]]) return false;   // complementary slackness
    return true;
}

int main() {
    Mat C = {{8, 4, 7, 3}, {5, 9, 6, 4}, {6, 7, 3, 8}, {4, 6, 9, 5}};
    std::vector<int> perm;
    std::vector<long long> u, v;
    hungarian(C, perm, u, v);
    long long cost = 0, dual = 0;
    for (int i = 0; i < 4; i++) { cost += C[i][perm[i]]; dual += u[i] + v[i]; std::printf("worker %d -> job %d\n", i, perm[i]); }
    std::printf("cost %lld, dual value %lld, certified %s\n", cost, dual, certified(C, perm, u, v) ? "yes" : "no");
}
worker 0 -> job 1
worker 1 -> job 3
worker 2 -> job 2
worker 3 -> job 0
cost 15, dual value 15, certified yes

Where to go next

  • Replace the dense O(n3)O(n^3) Hungarian method with a min-cost flow solver to handle sparse instances with thousands of workers; the certificate (node potentials) and the checker stay the same.
  • Add capacities (a worker can take up to bib_i jobs): the matrix stays totally unimodular, so the LP still has integral optima, and the dual still certifies them.
  • For weighted completion times ∑jwjCj\sum_j w_j C_j the slot trick no longer works directly (the problem is NP-hard on unrelated machines); LP relaxations and rounding for it are a topic of Approximation Algorithms.

Test yourself

Which three conditions does the checker verify to certify an optimal assignment?

  1. Integrality, symmetry, non-negativity
  2. π\pi is a permutation, ui+vj≤ciju_i + v_j \le c_{ij} for all pairs, and ui+vπ(i)=ciπ(i)u_i + v_{\pi(i)} = c_{i\pi(i)} on assigned pairs
  3. That SciPy reports success
  4. That every reduced cost is positive

Why does the assignment LP have an integral optimal vertex?

  1. Because costs are integers
  2. Because its constraint matrix (bipartite incidence) is totally unimodular
  3. Because the Hungarian method rounds it
  4. Because n=4n = 4

In the scheduling reduction, what does a job contribute if it is the kk-th from last on machine ii?

  1. pijp_{ij}
  2. k⋅pijk \cdot p_{ij}
  3. pij/kp_{ij} / k
  4. kk