Difference Constraints
Some scheduling problems are made entirely of rules of the form "event happens at most hours after event ": 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 unknowns and constraints, each of the form
Lower bounds fit too: is . A solution can always be shifted: if is a solution, so is for any constant , because every difference stays the same.
The constraint graph. Make a vertex for each unknown, and one extra vertex . For each constraint add an edge of weight , and add an edge of weight 0 for every . The graph has vertices and edges.
Theorem. If the constraint graph has no negative cycle, then is a solution. If it has a negative cycle, the system has no solution.
Proof
No negative cycle. Every is reachable from , so each is finite (and at most 0, thanks to the edge of weight 0). For each constraint edge of weight , the triangle inequality gives , which is exactly .
A negative cycle. Let be a negative cycle. It cannot use , which has no entering edges. Each edge of the cycle is a constraint: , , and so on, ending with . Adding them all, the left sides telescope to 0, so any solution would satisfy , which is impossible.
Running Bellman-Ford from costs . Starting every estimate at 0 instead of adding 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 (in hours):
| Rule | Constraint | Edge |
|---|---|---|
| starts within 4 hours of | , weight 4 | |
| starts at least 1 hour after | , weight | |
| starts within 2 hours of | , weight 2 | |
| starts within 5 hours of | , weight 5 | |
| starts at least 2 hours before | , weight | |
| starts within 1 hour of | , weight 1 | |
| starts within 3 hours of | , weight 3 |
The vertex plays the role of ; its edges are listed first.
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 ); shifting by a constant gives a schedule that starts at hour 0. The added rule " at least 6 hours after " contradicts " within 5 hours of ", and the negative cycle the program prints is that contradiction: adding the two constraints along it gives .
Note: Among all solutions with every , the shortest-path solution is the largest in every coordinate. Any such solution satisfies (the sum of the bounds along any path from to ), because summing the constraints along the path telescopes; the minimum over paths is .
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.
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.
#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 in the constraint graph?
- with weight 7
- with weight 7
- with weight
- with weight 7
The constraint graph has a negative cycle. What does that mean for the system?
- It has infinitely many solutions
- It has no solution: adding the cycle's constraints gives a negative number
- Only the cycle's variables are undetermined
- Bellman-Ford must be run again
How do you write the lower-bound constraint as a difference constraint?
- It cannot be written