Technique · CP 2000
System of Difference Constraints
Each constraint x_v - x_u <= w becomes an edge u -> v of weight w. A solution exists iff there is no negative cycle, and shortest distances from a virtual source give one.
Learn firstBellman-FordPrefix Sum
0%
mastery
0/1 solved
0/1 solved
Recognise it
The signal
constraints like 'the sum of a[l..r] lies in [L, R]' (prefix sums as the variables)
1Brute force
Search over assignments.
2The observation
Recognising that inequalities are edges.
3Why it works
d(v) <= d(u) + w(u, v) is exactly x_v - x_u <= w.
Reach for it when
- +schedule events 'at least / at most k apart'
- +assign integers satisfying pairwise difference bounds
Not when
- ×constraints are not differences (ratios, sums of three variables)
Practice
0/1 solved
- Subarray Sum ConstraintsCSESHard
Pitfalls
Misconceptions
- !forgetting the virtual source with 0-weight edges
- !flipping a '>=' constraint without negating the weight