TExcelTAD
Home › Graph Algorithms › Difference Constraints

Difference Constraints

Some scheduling problems are made entirely of rules of the form "event jj happens at most bb hours after event ii": the second coat of paint at least 4 hours after the first, but no more than 24; the speaker's talk no earlier than 30 minutes after the doors open. Each rule bounds a difference of two unknowns. A system of such rules is a special linear program that needs no LP solver: it is a shortest-path problem in disguise, and Bellman-Ford either solves it or proves that no solution exists.

Systems of difference constraints

A system of difference constraints has nn unknowns x1,…,xnx_1, \ldots, x_n and mm constraints, each of the form

xj−xi≤bkx_j - x_i \le b_k

Lower bounds fit too: xj−xi≥cx_j - x_i \ge c is xi−xj≤−cx_i - x_j \le -c. A solution can always be shifted: if xx is a solution, so is (x1+d,…,xn+d)(x_1 + d, \ldots, x_n + d) for any constant dd, because every difference stays the same.

The constraint graph. Make a vertex viv_i for each unknown, and one extra vertex v0v_0. For each constraint xj−xi≤bkx_j - x_i \le b_k add an edge (vi,vj)(v_i, v_j) of weight bkb_k, and add an edge (v0,vi)(v_0, v_i) of weight 0 for every ii. The graph has n+1n + 1 vertices and n+mn + m edges.

Theorem. If the constraint graph has no negative cycle, then xi=δ(v0,vi)x_i = \delta(v_0, v_i) is a solution. If it has a negative cycle, the system has no solution.

Proof

No negative cycle. Every viv_i is reachable from v0v_0, so each δ(v0,vi)\delta(v_0, v_i) is finite (and at most 0, thanks to the edge of weight 0). For each constraint edge (vi,vj)(v_i, v_j) of weight bkb_k, the triangle inequality gives δ(v0,vj)≤δ(v0,vi)+bk\delta(v_0, v_j) \le \delta(v_0, v_i) + b_k, which is exactly xj−xi≤bkx_j - x_i \le b_k.

A negative cycle. Let c=⟨vi1,vi2,…,vik,vi1⟩c = \langle v_{i_1}, v_{i_2}, \ldots, v_{i_k}, v_{i_1} \rangle be a negative cycle. It cannot use v0v_0, which has no entering edges. Each edge of the cycle is a constraint: xi2−xi1≤b1x_{i_2} - x_{i_1} \le b_1, xi3−xi2≤b2x_{i_3} - x_{i_2} \le b_2, and so on, ending with xi1−xik≤bkx_{i_1} - x_{i_k} \le b_k. Adding them all, the left sides telescope to 0, so any solution would satisfy 0≤b1+⋯+bk=w(c)<00 \le b_1 + \cdots + b_k = w(c) < 0, which is impossible.

Running Bellman-Ford from v0v_0 costs O(VE)=O((n+1)(n+m))=O(n2+nm)O(VE) = O((n + 1)(n + m)) = O(n^2 + nm). Starting every estimate at 0 instead of adding v0v_0 is the same thing, since the first pass would set them all to 0 anyway.

An example

Four tasks of a renovation have start times xA,xB,xC,xDx_A, x_B, x_C, x_D (in hours):

Rule Constraint Edge
BB starts within 4 hours of AA xB−xA≤4x_B - x_A \le 4 A→BA \to B, weight 4
BB starts at least 1 hour after AA xA−xB≤−1x_A - x_B \le -1 B→AB \to A, weight −1-1
CC starts within 2 hours of BB xC−xB≤2x_C - x_B \le 2 B→CB \to C, weight 2
CC starts within 5 hours of AA xC−xA≤5x_C - x_A \le 5 A→CA \to C, weight 5
DD starts at least 2 hours before CC xD−xC≤−2x_D - x_C \le -2 C→DC \to D, weight −2-2
DD starts within 1 hour of BB xD−xB≤1x_D - x_B \le 1 B→DB \to D, weight 1
AA starts within 3 hours of DD xA−xD≤3x_A - x_D \le 3 D→AD \to A, weight 3

The vertex SS plays the role of v0v_0; its edges are listed first.

python · try it yourself
INF = float("inf")

def solve(variables, constraints):
    """constraints: (j, i, b) meaning x_j - x_i <= b. Returns a solution or a contradiction."""
    edges = [("S", v, 0) for v in variables] + [(i, j, b) for j, i, b in constraints]
    d = {v: INF for v in variables}
    d["S"] = 0
    pi = {}
    for _ in range(len(variables)):                       # |V| - 1 passes, |V| = n + 1
        for u, v, w in edges:
            if d[u] + w < d[v]:
                d[v], pi[v] = d[u] + w, u
    for u, v, w in edges:
        if d[u] + w < d[v]:
            pi[v] = u
            x = v
            for _ in range(len(variables) + 1):
                x = pi[x]
            cycle, y = [x], pi[x]
            while y != x:
                cycle.append(y); y = pi[y]
            return None, cycle[::-1]
    return {v: d[v] for v in variables}, None

rules = [("B", "A", 4), ("A", "B", -1), ("C", "B", 2), ("C", "A", 5), ("D", "C", -2), ("D", "B", 1), ("A", "D", 3)]
x, _ = solve("ABCD", rules)
print("solution:", x)
for j, i, b in rules:
    assert x[j] - x[i] <= b
print("all", len(rules), "constraints hold")
shift = -min(x.values())
print("shifted to start at 0:", {v: t + shift for v, t in x.items()})

rules.append(("A", "C", -6))                              # C at least 6 hours after A
x, cycle = solve("ABCD", rules)
print("after adding x_A - x_C <= -6:", "no solution; negative cycle", " -> ".join(cycle + [cycle[0]]))
solution: {'A': -1, 'B': 0, 'C': 0, 'D': -2}
all 7 constraints hold
shifted to start at 0: {'A': 1, 'B': 2, 'C': 2, 'D': 0}
after adding x_A - x_C <= -6: no solution; negative cycle C -> A -> C

Bellman-Ford's answer has all values at most 0 (because of the 0-weight edges from SS); shifting by a constant gives a schedule that starts at hour 0. The added rule "CC at least 6 hours after AA" contradicts "CC within 5 hours of AA", and the negative cycle the program prints is that contradiction: adding the two constraints along it gives 0≤5−60 \le 5 - 6.

Note: Among all solutions with every xi≤0x_i \le 0, the shortest-path solution is the largest in every coordinate. Any such solution satisfies xi≤x_i \le (the sum of the bounds along any path from v0v_0 to viv_i), because summing the constraints along the path telescopes; the minimum over paths is δ(v0,vi)\delta(v_0, v_i).

Checking on random systems

The program generates random systems, solves them with Bellman-Ford, and verifies every answer: a solution must satisfy all constraints, and for "no solution" the printed cycle's bounds must add up to a negative number.

python · try it yourself
import random

def solve(n, cons):
    edges = [(n, v, 0) for v in range(n)] + [(i, j, b) for j, i, b in cons]
    d = [float("inf")] * n + [0]
    pi = [None] * (n + 1)
    for _ in range(n):
        for u, v, w in edges:
            if d[u] + w < d[v]:
                d[v], pi[v] = d[u] + w, u
    for u, v, w in edges:
        if d[u] + w < d[v]:
            pi[v] = u
            x = v
            for _ in range(n + 1):
                x = pi[x]
            cyc, y = [x], pi[x]
            while y != x:
                cyc.append(y); y = pi[y]
            return None, cyc[::-1]
    return d[:n], None

rng = random.Random(21)
feasible = infeasible = 0
for trial in range(400):
    n = rng.randint(2, 8)
    cons = [(j, i, rng.randint(-6, 8)) for _ in range(rng.randint(1, 12))
            for i, j in [rng.sample(range(n), 2)]]
    x, cyc = solve(n, cons)
    if x is not None:
        assert all(x[j] - x[i] <= b for j, i, b in cons)
        feasible += 1
    else:
        weight = 0
        for a, b in zip(cyc, cyc[1:] + cyc[:1]):          # edge a -> b is a constraint x_b - x_a <= bound
            weight += min(bd for j, i, bd in cons if i == a and j == b)
        assert weight < 0
        infeasible += 1
print(f"{feasible} feasible systems solved and verified, {infeasible} infeasible ones refuted by a negative cycle")
255 feasible systems solved and verified, 145 infeasible ones refuted by a negative cycle

In C++

The C++ version solves the renovation system with the "every estimate starts at 0" form of Bellman-Ford.

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

struct Constraint { int j, i, b; };                            // x_j - x_i <= b

int main() {
    const int n = 4;                                          // x_A..x_D
    std::vector<Constraint> c = {{1,0,4}, {0,1,-1}, {2,1,2}, {2,0,5}, {3,2,-2}, {3,1,1}, {0,3,3}};
    std::vector<long long> x(n, 0);                           // = edges of weight 0 from v0
    for (int pass = 0; pass < n; ++pass)
        for (auto [j, i, b] : c) x[j] = std::min(x[j], x[i] + b);
    bool ok = true;
    for (auto [j, i, b] : c) if (x[j] > x[i] + b) ok = false;
    if (!ok) { std::printf("no solution\n"); return 0; }
    long long lo = *std::min_element(x.begin(), x.end());
    for (int v = 0; v < n; ++v) std::printf("x_%c = %lld (shifted: %lld)\n", 'A' + v, x[v], x[v] - lo);
}
x_A = -1 (shifted: 1)
x_B = 0 (shifted: 2)
x_C = 0 (shifted: 2)
x_D = -2 (shifted: 0)

Test yourself

Which edge represents the constraint x3−x5≤7x_3 - x_5 \le 7 in the constraint graph?

  1. (v3,v5)(v_3, v_5) with weight 7
  2. (v5,v3)(v_5, v_3) with weight 7
  3. (v5,v3)(v_5, v_3) with weight −7-7
  4. (v0,v3)(v_0, v_3) with weight 7

The constraint graph has a negative cycle. What does that mean for the system?

  1. It has infinitely many solutions
  2. It has no solution: adding the cycle's constraints gives 0≤0 \le a negative number
  3. Only the cycle's variables are undetermined
  4. Bellman-Ford must be run again

How do you write the lower-bound constraint x2−x1≥3x_2 - x_1 \ge 3 as a difference constraint?

  1. x2−x1≤−3x_2 - x_1 \le -3
  2. x1−x2≤−3x_1 - x_2 \le -3
  3. x1−x2≤3x_1 - x_2 \le 3
  4. It cannot be written