Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

Divide-and-Conquer Optimization & the Aliens Trick

Monotone optimal split points, and Lagrangian relaxation of a count constraint.

Place kk post offices among nn houses on a street to minimize the total walking distance. The layered DP has kk layers of nn states, each a minimum over up to nn candidates: O(kn2)O(kn^2). Monotone optimal splits cut each layer to O(nlog⁡n)O(n \log n). And when kk is as large as nn, a price on each office removes kk from the problem altogether: name a price, let the DP decide how many offices to build, and adjust the price until it builds exactly kk.

What you’ll learn

  • Prove that the quadrangle inequality makes the optimal split points of a layered DP monotone, and that divide and conquer then computes a layer in O(nlog⁡n)O(n \log n).
  • Relax an "exactly KK" constraint with a price λ\lambda per group, and prove weak duality, Everett's equality and the monotonicity of the chosen count.
  • Prove that the quadrangle inequality makes the optimal cost convex in the number of groups, by swapping the tails of two partitions, and recognize a duality gap when it fails.
  • Handle ties rigorously, implement the penalty search, and place it in the history of Lagrangian relaxation and kk-link shortest paths.

Monotone splits and divide and conquer

Cover the prefix [0,i)[0, i) of nn items with exactly kk consecutive groups, where a group [j,i)[j, i) costs C(j,i)C(j, i):

fk(i)=min⁡0≤j<i(fk−1(j)+C(j,i)),f0(0)=0,f0(i)=∞ for i>0.f_k(i) = \min_{0 \le j < i}\big(f_{k-1}(j) + C(j, i)\big), \qquad f_0(0) = 0, \quad f_0(i) = \infty \text{ for } i > 0.

For post offices, the houses x0≤x1≤⋯≤xn−1x_0 \le x_1 \le \dots \le x_{n-1} are sorted, and a group's cost is the total distance from its houses to its median, the best place for its office. Let optk(i)\text{opt}_k(i) be the smallest jj that achieves the minimum.

DerivationProof: an exchange
  1. g(j)+C(j,i)<g(j′)+C(j′,i)g(j) + C(j, i) < g(j') + C(j', i)

    Suppose i<i′i < i' but j′=opt(i′)<j=opt(i)j' = \text{opt}(i') < j = \text{opt}(i), so that j′<j<i<i′j' < j < i < i'. Since jj is the smallest minimizer for ii, the earlier candidate j′j' is strictly worse there:

  2. C(j,i′)−C(j′,i′)≤C(j,i)−C(j′,i)C(j, i') - C(j', i') \le C(j, i) - C(j', i)

    The quadrangle inequality on j′≤j≤i≤i′j' \le j \le i \le i' says that moving the right end from ii to i′i' helps jj at least as much as it helps j′j':

  3. g(j)+C(j,i′)<g(j′)+C(j′,i′)g(j) + C(j, i') < g(j') + C(j', i')

    Combine the two: jj beats j′j' strictly for i′i' as well, and j<i<i′j < i < i' is a legal candidate there. This contradicts the choice of j′j' as a minimizer for i′i'.

Divide and conquer. Compute fk(mid)f_k(\text{mid}) for the middle state of a range by scanning all its candidates. By the theorem, the states left of mid need only candidates up to opt(mid)\text{opt}(\text{mid}), and the states right of it only candidates from opt(mid)\text{opt}(\text{mid}) on, so recurse on both halves with those narrowed candidate ranges. This is divide-and-conquer optimization.

DerivationThe cost of one layer
  1. ∑subproblems at depth t(opthi−optlo+1)≤n+2t\sum_{\text{subproblems at depth } t} \big(\text{opthi} - \text{optlo} + 1\big) \le n + 2^t

    At one depth tt of the recursion, the candidate ranges of the subproblems are consecutive and share only their endpoints, so together they hold at most nn candidates plus one per subproblem:

  2. Tlayer(n)=O(nlog⁡n),T(n,k)=O(knlog⁡n)T_{\text{layer}}(n) = O(n \log n), \qquad T(n, k) = O(kn \log n)

    Each depth halves the ranges of states, so there are about log⁡2n\log_2 n depths, and the 2t2^t terms add up to O(n)O(n):

python
def median_cost(x):                          # x sorted; serve x[j..i-1] from their median
    S = [0]
    for v in x:
        S.append(S[-1] + v)
    def cost(j, i):
        m = (j + i - 1) // 2                 # a median of the group
        return x[m] * (m - j) - (S[m] - S[j]) + (S[i] - S[m + 1]) - x[m] * (i - m - 1)
    return cost

def layer(prev, cost, n):                    # cur[i] = min over j < i of prev[j] + cost(j, i)
    cur = [float('inf')] * (n + 1)
    def solve(lo, hi, optlo, opthi):         # states lo..hi have their best j in [optlo, opthi]
        if lo > hi:
            return
        mid = (lo + hi) // 2
        best, arg = float('inf'), optlo
        for j in range(optlo, min(mid - 1, opthi) + 1):
            v = prev[j] + cost(j, mid)
            if v < best:                     # strict: the smallest best j
                best, arg = v, j
        cur[mid] = best
        solve(lo, mid - 1, optlo, arg)
        solve(mid + 1, hi, arg, opthi)
    solve(1, n, 0, n - 1)
    return cur

Starting from [0, inf, ..., inf], kk calls of layer give fk(n)f_k(n); the median cost takes O(1)O(1) with prefix sums and satisfies the quadrangle inequality, as a direct check confirms. For houses at 1,2,3,10,11,12,30,31,33,501, 2, 3, 10, 11, 12, 30, 31, 33, 50, the optimal costs with k=1,…,6k = 1, \dots, 6 offices are 129,49,26,7,5,4129, 49, 26, 7, 5, 4. On 4,000 random houses a layer evaluates about 47,000 candidates, close to nlog⁡2nn \log_2 n, against 8 million for the plain double loop.

Pricing the count: Lagrangian relaxation

Write f(k)=fk(n)f(k) = f_k(n) for the least cost with exactly kk groups. When kk is close to nn, even O(knlog⁡n)O(kn \log n) is quadratic. Relax the constraint instead: charge a price λ\lambda per group and let the DP choose how many to use,

g(λ)=min⁡partitions(cost+λ⋅#groups)=min⁡k(f(k)+λk).g(\lambda) = \min_{\text{partitions}}\big(\text{cost} + \lambda \cdot \#\text{groups}\big) = \min_{k}\big(f(k) + \lambda k\big).

Computing g(λ)g(\lambda) is a one-dimensional DP without layers, h(i)=min⁡j<i(h(j)+C(j,i)+λ)h(i) = \min_{j < i}\big(h(j) + C(j, i) + \lambda\big). This is Lagrangian relaxation: λ\lambda is a Lagrange multiplier for the constraint "the number of groups is KK".

DerivationWhat a price tells you
  1. g(λ)−λK≤f(K)for every λg(\lambda) - \lambda K \le f(K) \qquad \text{for every } \lambda

    Weak duality. The best KK-group partition is one of the candidates in g(λ)g(\lambda), so every price gives a lower bound:

  2. g(λ)=f(K)+λKg(\lambda) = f(K) + \lambda K

    Everett's equality (1963), in its simplest form: if some optimum of the penalized problem uses exactly KK groups, its cost is f(K)f(K) and the bound is tight. No convexity is needed for this direction.

  3. (λ2−λ1)(k1−k2)≥0  ⟹  k2≤k1(\lambda_2 - \lambda_1)(k_1 - k_2) \ge 0 \;\Longrightarrow\; k_2 \le k_1

    The count moves the right way, always. Let k1k_1 be an optimal count at price λ1\lambda_1 and k2k_2 one at λ2>λ1\lambda_2 > \lambda_1. Each beats the other at its own price: f(k1)+λ1k1≤f(k2)+λ1k2f(k_1) + \lambda_1 k_1 \le f(k_2) + \lambda_1 k_2 and f(k2)+λ2k2≤f(k1)+λ2k1f(k_2) + \lambda_2 k_2 \le f(k_1) + \lambda_2 k_1. Adding them leaves

The picture. Plot the points (k,f(k))(k, f(k)). For a price λ\lambda, g(λ)g(\lambda) is the intercept of the lowest line of slope −λ-\lambda that touches the points from below, and the points it touches are the optimal counts. Raising λ\lambda tilts the line and rolls it toward fewer groups. A point is touched for some price exactly when it lies on the lower convex hull of the points, so a binary search on λ\lambda can reach every KK precisely when ff is convex: f(k−1)+f(k+1)≥2f(k)f(k-1) + f(k+1) \ge 2f(k), that is, the drops f(k−1)−f(k)f(k-1) - f(k) never grow.

Predict before you look

For the ten houses above, f(1),…,f(6)=129,49,26,7,5,4f(1), \dots, f(6) = 129, 49, 26, 7, 5, 4, and ff keeps falling by 1 per extra office after that. At a price of λ=20\lambda = 20 per office, how many offices does the penalized optimum build?

Show the answer

3 offices

f(k)+20kf(k) + 20k is 149,89,86,87,105,124149, 89, 86, 87, 105, 124 for k=1,…,6k = 1, \dots, 6, and larger beyond, so the minimum, 86, is at k=3k = 3. A third office saves 49−26=23>2049 - 26 = 23 > 20, a fourth only 26−7=19<2026 - 7 = 19 < 20. Every price strictly between 19 and 23 builds exactly 3 offices; at exactly 19, three and four tie.

Why the optimal cost is convex

DerivationProof: swap the tails of two partitions
  1. at≤bt+1<bt+2≤at+1a_t \le b_{t+1} < b_{t+2} \le a_{t+1}

    Take optimal partitions with boundaries 0=a0<⋯<ak−1=n0 = a_0 < \dots < a_{k-1} = n (k−1k - 1 groups) and 0=b0<⋯<bk+1=n0 = b_0 < \dots < b_{k+1} = n (k+1k + 1 groups). Let tt be the smallest index with bt+2≤at+1b_{t+2} \le a_{t+1}; one exists, since t=k−2t = k - 2 qualifies. By minimality (t=0t = 0, or the condition failed at t−1t - 1), a group of the finer partition lies inside a group of the coarser one:

  2. A′=(a0,…,at, bt+2,…,bk+1),B′=(b0,…,bt+1, at+1,…,ak−1)A' = (a_0, \dots, a_t,\ b_{t+2}, \dots, b_{k+1}), \qquad B' = (b_0, \dots, b_{t+1},\ a_{t+1}, \dots, a_{k-1})

    Swap the tails after that point. Each new partition has exactly kk groups, and together they use every group of the two old partitions, except that [at,at+1)[a_t, a_{t+1}) and [bt+1,bt+2)[b_{t+1}, b_{t+2}) are replaced by [at,bt+2)[a_t, b_{t+2}) and [bt+1,at+1)[b_{t+1}, a_{t+1}):

  3. C(at,bt+2)+C(bt+1,at+1)≤C(at,at+1)+C(bt+1,bt+2)C(a_t, b_{t+2}) + C(b_{t+1}, a_{t+1}) \le C(a_t, a_{t+1}) + C(b_{t+1}, b_{t+2})

    The quadrangle inequality on at≤bt+1≤bt+2≤at+1a_t \le b_{t+1} \le b_{t+2} \le a_{t+1} says that the two new groups cost no more than the two they replace:

  4. 2f(k)≤cost⁡(A′)+cost⁡(B′)≤f(k−1)+f(k+1)2f(k) \le \operatorname{cost}(A') + \operatorname{cost}(B') \le f(k-1) + f(k+1)

    So two partitions with kk groups cost at most f(k−1)+f(k+1)f(k-1) + f(k+1) together, and each of them costs at least f(k)f(k):

The kk-link view. Make the boundaries 0,…,n0, \dots, n the vertices of a DAG with an edge j→ij \to i of weight C(j,i)C(j, i) for every j<ij < i. A partition into kk groups is a path from 0 to nn with exactly kk edges, so f(k)f(k) is the weight of a minimum-weight kk-link path, and a quadrangle-inequality weight makes the graph a concave Monge DAG in the terminology of the literature. Aggarwal, Schieber and Tokuyama (1994) combined exactly this convexity with parametric search to find such paths.

Ties, the algorithm, and its history

Ties. Collinear points of ff make several counts optimal at one price, and the count a DP reports then depends on how it breaks ties. Break them consistently toward fewer groups, and search for the smallest price λ∗\lambda^* whose reported count is at most KK.

DerivationWhy g(λ*) − λ*K is exact
  1. reported(λ)=min⁡{ k:dk+1≤λ }\text{reported}(\lambda) = \min\{\, k : d_{k+1} \le \lambda \,\}

    Let dk=f(k−1)−f(k)d_k = f(k-1) - f(k) be the drops, which convexity makes non-increasing. The optimal counts at price λ\lambda are the kk with dk+1≤λ≤dkd_{k+1} \le \lambda \le d_k, and breaking ties toward fewer groups reports the smallest of them:

  2. λ∗=dK+1≤dK\lambda^* = d_{K+1} \le d_K

    So the reported count is at most KK exactly when λ≥dK+1\lambda \ge d_{K+1}, and the search stops at λ∗=dK+1\lambda^* = d_{K+1}. With integer costs the drops are integers, so searching over integers suffices. (For K=nK = n the search stops at its lower end; when splitting a group never hurts, all drops are non-negative and that end is λ=0\lambda = 0.)

  3. f(K)=g(λ∗)−λ∗Kf(K) = g(\lambda^*) - \lambda^* K

    At that price KK is among the optimal counts, even when the DP reports a smaller one, so Everett's equality applies to KK:

python
def penalized(cost, n, lam):                # min of cost + lam * groups; ties go to fewer groups
    best = [(0, 0)] + [None] * n            # best[i] = (value, groups) for the prefix of length i
    for i in range(1, n + 1):
        best[i] = min((best[j][0] + cost(j, i) + lam, best[j][1] + 1) for j in range(i))
    return best[n]

def exactly_k(cost, n, K):                  # needs a convex f; here splitting never hurts, so lam >= 0
    lo, hi = 0, cost(0, n)                  # hi >= f(1) - f(2), the largest drop
    while lo < hi:                          # the smallest lam whose optimum uses at most K groups
        mid = (lo + hi) // 2
        if penalized(cost, n, mid)[1] <= K:
            hi = mid
        else:
            lo = mid + 1
    value, _ = penalized(cost, n, lo)
    return value - lo * K                   # g(lam) - lam*K, whatever count the DP reported

Tuples compare values first and group counts second, which breaks ties toward fewer groups. With median_cost from the first step it returns 129,49,26,7,5,4129, 49, 26, 7, 5, 4 for K=1,…,6K = 1, \dots, 6, and it agrees with the layered DP on 400 random instances, ties included. The inner loop here is the plain O(n2)O(n^2) one; replace it by a faster exact method that keeps the same tie rule (the convex hull trick for squared sums; a queue of candidates with binary search, O(nlog⁡n)O(n \log n), or Larmore and Schieber's O(n)O(n) algorithm for general quadrangle-inequality costs), and the whole search costs O(Tlog⁡U)O(T \log U) for a penalized DP of time TT and prices up to UU.

Check your understanding

Asked for K=5K = 5 groups, the search stops at the price λ∗=7\lambda^* = 7. There the penalized optimum costs g(7)=120g(7) = 120, and the DP, breaking ties toward fewer groups, reports 4 groups. What is f(5)f(5)?

  1. 85=120−7⋅585 = 120 - 7 \cdot 5
  2. 92=120−7⋅492 = 120 - 7 \cdot 4
  3. 120120
  4. Unknown: search again with a slightly smaller price until the DP reports 5 groups
Show the answer

A. 85=120−7⋅585 = 120 - 7 \cdot 5

λ∗\lambda^* is the smallest price whose reported count is at most 5, so λ∗=d6\lambda^* = d_6 and 5 is among the optimal counts there; it ties with 4. Everett's equality for K=5K = 5 gives f(5)=g(7)−7⋅5=85f(5) = g(7) - 7 \cdot 5 = 85. The reported 4 only shows how the tie was broken.

History. Everett (1963) proved the generalized Lagrange multiplier theorem for allocating limited resources: an optimum of the penalized problem is optimal for whatever resource level it happens to use. Held and Karp (1970, 1971) used Lagrangian penalties to compute strong lower bounds for the traveling salesman problem, and Fisher (1981) surveyed the method for integer programming. When a multiplier must be located exactly over the reals, Megiddo's parametric search (1983) is the classical tool, and Aggarwal, Schieber and Tokuyama (1994) used it for kk-link paths in concave Monge DAGs.

Contest programmers call the method the Aliens trick, after a task at the 2016 International Olympiad in Informatics in Kazan whose full solution combined a convex-hull-trick DP with this penalty search; it is also known as WQS binary search.

Key takeaways

  • If CC satisfies the quadrangle inequality, the smallest optimal split of min⁡j(g(j)+C(j,i))\min_j\big(g(j) + C(j, i)\big) never decreases in ii, for any gg: divide and conquer computes each layer in O(nlog⁡n)O(n \log n).
  • A price λ\lambda per group turns "exactly KK groups" into one unconstrained DP: g(λ)−λK≤f(K)g(\lambda) - \lambda K \le f(K) always, with equality when an optimum uses KK groups (Everett), and the chosen count never increases with λ\lambda.
  • The quadrangle inequality makes ff convex in kk (swap the tails of a (k−1)(k-1)-group and a (k+1)(k+1)-group partition), so every KK is reachable; without convexity a duality gap can make the search return a wrong value.
  • Break ties toward fewer groups, search for the smallest λ\lambda whose count is at most KK, and return g(λ)−λKg(\lambda) - \lambda K, whatever count the DP reported.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Divide-and-conquer optimization computes one layer of nn states. How many candidate evaluations does it make, and why?

  1. O(n)O(n), since each state is computed once
  2. O(nlog⁡n)O(n \log n): each depth of the recursion scans O(n)O(n) candidates in total, and there are O(log⁡n)O(\log n) depths
  3. O(n2)O(n^2) in the worst case, since one state may scan Θ(n)\Theta(n) candidates
  4. O(nn)O(n\sqrt{n}), from balancing the two halves
Show the answer

B. O(nlog⁡n)O(n \log n): each depth of the recursion scans O(n)O(n) candidates in total, and there are O(log⁡n)O(\log n) depths

At a fixed depth the candidate ranges of the subproblems overlap only at their endpoints, so they sum to O(n)O(n); the state ranges halve, so there are about log⁡2n\log_2 n depths.

Question 2

Without assuming that ff is convex, what happens to the number of groups chosen by the penalized optimum as the price λ\lambda increases?

  1. It decreases by exactly one each time λ\lambda passes a drop f(k−1)−f(k)f(k-1) - f(k)
  2. It can go up or down, depending on ff
  3. It never increases, though it may skip some counts
  4. It stays constant until λ\lambda exceeds f(1)f(1)
Show the answer

C. It never increases, though it may skip some counts

Adding the two optimality inequalities at prices λ1<λ2\lambda_1 < \lambda_2 gives (λ2−λ1)(k1−k2)≥0(\lambda_2 - \lambda_1)(k_1 - k_2) \ge 0, so k2≤k1k_2 \le k_1 for any ff. Without convexity, counts that lie above the lower convex hull of the points (k,f(k))(k, f(k)) are skipped: no price ever selects them.

Question 3

At the price λ=12\lambda = 12, the penalized DP returns an optimal partition with exactly 7 groups and penalized cost 300. Nothing is known about the convexity of ff. What follows?

  1. Only that f(7)≥216f(7) \ge 216
  2. f(7)=300f(7) = 300
  3. Nothing, unless ff is convex
  4. f(7)=216f(7) = 216, and this partition is optimal among all partitions with 7 groups
Show the answer

D. f(7)=216f(7) = 216, and this partition is optimal among all partitions with 7 groups

Everett's equality needs no convexity: any 7-group partition costing less than 216 would give a penalized cost below 300 at λ=12\lambda = 12. So f(7)=300−12⋅7=216f(7) = 300 - 12 \cdot 7 = 216. Convexity matters only for whether a price exists that selects a given KK.

Question 4

A cost table violating the quadrangle inequality gives f(3)=15f(3) = 15, f(4)=33f(4) = 33 and f(5)=37f(5) = 37. What does the penalty search do for K=4K = 4?

  1. It returns 33 after enough halvings of the price range
  2. It returns 33 if ties are broken toward more groups instead
  3. It cannot be exact: no price makes 4 groups optimal, so g(λ)−4λg(\lambda) - 4\lambda stays at most 26, below f(4)=33f(4) = 33
  4. It returns 26, which is the true f(4)f(4)
Show the answer

C. It cannot be exact: no price makes 4 groups optimal, so g(λ)−4λg(\lambda) - 4\lambda stays at most 26, below f(4)=33f(4) = 33

(4,33)(4, 33) lies above the chord from (3,15)(3, 15) to (5,37)(5, 37), whose midpoint is 26, so the point is not on the lower convex hull and no line of any slope touches it first. Weak duality still holds, but the best bound is the hull's value, 26: a duality gap.

Further reading

  • H. Everett III, "Generalized Lagrange multiplier method for solving problems of optimum allocation of resources," Operations Research 11 (1963), 399–417.
  • M. L. Fisher, "The Lagrangian relaxation method for solving integer programming problems," Management Science 27 (1981), 1–18.
  • A. Aggarwal, B. Schieber & T. Tokuyama, "Finding a minimum-weight k-link path in graphs with the concave Monge property and applications," Discrete & Computational Geometry 12 (1994), 263–280.
  • B. Schieber, "Computing a minimum weight k-link path in graphs with the concave Monge property," Journal of Algorithms (1998).
  • CP-Algorithms, "Divide and Conquer DP".