Algorithm Search⌘K

Algorithmintro

Dubins-Spanier moving knife

Also called Dubins-Spanier procedure.

A proportional cake cutting protocol. A knife moves from left to right, and the first agent to value the piece behind it at 1/n calls stop and takes it.

Time
Θ(n^2) worst
Space
Θ(n) extra
Where
n = the number of agents
Properties
deterministicofflineiterative

The Dubins-Spanier moving knife is a protocol that gives each of nn agents a connected piece of a cake worth at least 1/n1/n to that agent, so it finds a proportional division. A referee moves a knife slowly from the left end of the cake. The first agent that values the piece to the left of the knife at 1/n1/n calls stop, takes that piece and leaves. The knife then starts again from the cut, and the last agent takes what is left. In the Robertson-Webb query model, each stop of the knife is found with one cut query per remaining agent, for n(n+1)/2−1n(n+1)/2 - 1 cut queries in total.

In plain words

A group of friends shares a long cake. One person holds a knife over the left end and moves it slowly to the right. Each friend watches. As soon as the piece behind the knife looks like a fair share to some friend, that friend calls "stop". The cake is cut there, and the friend takes the piece and leaves.

The other friends did not call stop, so the piece looked small to them. They think enough cake is left for them. The knife starts again at the cut, and the method repeats. When only one friend is left, that friend takes the rest. Each friend can make sure of a fair share alone: it only has to call stop at the right time.

The problem

The cake is [0,1][0, 1]. Agent i∈{1,…,n}i \in \{1, \dots, n\} has a nonnegative, additive and nonatomic valuation ViV_i with Vi([0,1])=1V_i([0, 1]) = 1. The protocol must output disjoint intervals X1,…,XnX_1, \dots, X_n that cover [0,1][0, 1], with Vi(Xi)≥1/nV_i(X_i) \ge 1/n for every ii. It learns the valuations only by queries. Here it needs only the cut query: Cuti(a,t)\mathrm{Cut}_i(a, t) returns the least point x≥ax \ge a with Vi([a,x])=tV_i([a, x]) = t.

The algorithm

A continuous knife is not a finite protocol, but this one is easy to simulate. When the knife starts at aa, agent ii would call stop at its mark mi=Cuti(a,1/n)m_i = \mathrm{Cut}_i(a, 1/n). The knife therefore stops at the least mark. So the protocol asks every remaining agent for its mark and takes the least one.

  1. DUBINS-SPANIER(n)
  2. 1a ← 0; R ← {1, 2, …, n}
  3. 2while |R| > 1 do
  4. 3for each agent i of R do m_i ← CUT_i(a, 1/n) ▷ where agent i would call stop
  5. 4h ← the agent of R with the least m_i ▷ ties go to the smallest index
  6. 5give [a, m_h] to h; remove h from R; a ← m_h
  7. 6give [a, 1] to the last agent of R

The rule for ties does not change the guarantees. A real knife must also break ties, for example by a fixed order of the agents.

Example

Split [0,1][0, 1] into four equal segments, and let the densities on them be (1,1,1,1)(1, 1, 1, 1) for agent 1, (0,1,1,2)(0, 1, 1, 2) for agent 2, (2,2,0,0)(2, 2, 0, 0) for agent 3 and (1,0,0,3)(1, 0, 0, 3) for agent 4. Each list sums to 4, so each agent values the whole cake at 1. Here n=4n = 4 and 1/n=1/41/n = 1/4.

round aa marks of the remaining agents least mark piece
1 0 m1=1/4m_1 = 1/4, m2=1/2m_2 = 1/2, m3=1/8m_3 = 1/8, m4=1/4m_4 = 1/4 agent 3 [0,1/8][0, 1/8]
2 1/81/8 m1=3/8m_1 = 3/8, m2=1/2m_2 = 1/2, m4=19/24m_4 = 19/24 agent 1 [1/8,3/8][1/8, 3/8]
3 3/83/8 m2=5/8m_2 = 5/8, m4=5/6m_4 = 5/6 agent 2 [3/8,5/8][3/8, 5/8]
5/85/8 agent 4 [5/8,1][5/8, 1]

Agents 3, 1 and 2 get exactly 1/41/4, and agent 4 gets 3/43/4. The run makes 4+3+2=94 + 3 + 2 = 9 cut queries and no eval queries. The result is proportional but not envy-free: agent 2 values the piece of agent 4 at 1/8+1/2=5/81/8 + 1/2 = 5/8, and agent 3 values the piece of agent 1 at 1/21/2.

Correctness

Invariant. At the start of each round, every agent ii in RR has Vi([a,1])≥∣R∣/nV_i([a, 1]) \ge |R|/n.

It holds at the start with a=0a = 0 and ∣R∣=n|R| = n. In a round, the receiver hh has the least mark, so every other agent jj of RR has mh≤mjm_h \le m_j and Vj([a,mh])≤Vj([a,mj])=1/nV_j([a, m_h]) \le V_j([a, m_j]) = 1/n. Hence Vj([mh,1])≥∣R∣/n−1/nV_j([m_h, 1]) \ge |R|/n - 1/n, which is the invariant for the next round. Each receiver in line L5 gets exactly 1/n1/n, and the last agent gets at least 1/n1/n by the invariant with ∣R∣=1|R| = 1. The cut queries have answers because each agent in RR values [a,1][a, 1] at least 1/n1/n. The full proof is in proofs/correctness.md.

Proof: The Dubins-Spanier procedure is proportional and uses n(n+1)/2 - 1 cut queriesfull

Setting. The cake is [0,1][0, 1], and agent i∈{1,…,n}i \in \{1, \dots, n\} has a nonnegative, additive and nonatomic valuation ViV_i with Vi([0,1])=1V_i([0, 1]) = 1. For a∈[0,1]a \in [0, 1], the map t↦Vi([a,t])t \mapsto V_i([a, t]) is continuous and nondecreasing on [a,1][a, 1], since ViV_i is nonatomic. So Cuti(a,t)\mathrm{Cut}_i(a, t) has an answer whenever 0≤t≤Vi([a,1])0 \le t \le V_i([a, 1]), and the least answer xx has Vi([a,x])=tV_i([a, x]) = t. Single points have value 0. We refer to the lines L1 to L6 of the page.

Lemma 1 (the stop point of the knife). Let the knife start at aa, and let each agent i∈Ri \in R call stop at the first point yy with Vi([a,y])≥1/nV_i([a, y]) \ge 1/n. Then the knife stops at min⁡i∈Rmi\min_{i \in R} m_i, where mi=Cuti(a,1/n)m_i = \mathrm{Cut}_i(a, 1/n) is the least answer.

Proof. By continuity, the first point yy with Vi([a,y])≥1/nV_i([a, y]) \ge 1/n is the least yy with Vi([a,y])=1/nV_i([a, y]) = 1/n, which is mim_i. The knife stops at the first call, so at min⁡imi\min_i m_i. □\square

So lines L3 to L5 simulate the knife exactly, with the tie rule of line L4.

Lemma 2 (invariant). At the test of line L2, every agent i∈Ri \in R has Vi([a,1])≥∣R∣/nV_i([a, 1]) \ge |R|/n.

Proof. By induction on the rounds. The first time, a=0a = 0, ∣R∣=n|R| = n and Vi([0,1])=1V_i([0, 1]) = 1. Suppose the invariant holds at the start of a round. Each cut query of line L3 asks for 1/n≤∣R∣/n≤Vi([a,1])1/n \le |R|/n \le V_i([a, 1]), so it has an answer. Let hh be the agent of line L4. For each j∈R∖{h}j \in R \setminus \{h\}, we have mh≤mjm_h \le m_j, so monotonicity gives Vj([a,mh])≤Vj([a,mj])=1/nV_j([a, m_h]) \le V_j([a, m_j]) = 1/n. Additivity then gives

Vj([mh,1])=Vj([a,1])−Vj([a,mh])≥∣R∣n−1n=∣R∣−1n.V_j([m_h, 1]) = V_j([a, 1]) - V_j([a, m_h]) \ge \frac{|R|}{n} - \frac{1}{n} = \frac{|R| - 1}{n}.

Line L5 sets a←mha \leftarrow m_h and removes hh, so the invariant holds for the new RR. □\square

Theorem 1 (proportional). The output is a partition of [0,1][0, 1] into nn intervals, and Vi(Xi)≥1/nV_i(X_i) \ge 1/n for every agent ii.

Proof. Each round removes one agent, so the loop runs n−1n - 1 times. The successive left ends a0=0≤a1≤⋯≤an−1a_0 = 0 \le a_1 \le \dots \le a_{n-1} satisfy ak+1=mh≥aka_{k+1} = m_h \ge a_k, because a cut from aka_k returns a point at least aka_k. The pieces [ak,ak+1][a_k, a_{k+1}] of line L5 and the piece [an−1,1][a_{n-1}, 1] of line L6 cover [0,1][0, 1] and meet only at end points. Each agent of line L5 gets Vh([a,mh])=1/nV_h([a, m_h]) = 1/n. The last agent gets Vi([a,1])≥1/nV_i([a, 1]) \ge 1/n by Lemma 2 with ∣R∣=1|R| = 1. □\square

Theorem 2 (safe for an honest agent). If agent ii answers by ViV_i, then Vi(Xi)≥1/nV_i(X_i) \ge 1/n, whatever points the other agents give as marks.

Proof. The proof of Lemma 2 for the single agent ii uses only its own mark mim_i and the choice of the least mark in line L4: if agent ii is not chosen, some mark mh≤mim_h \le m_i was chosen, so Vi([a,mh])≤1/nV_i([a, m_h]) \le 1/n. This needs nothing about the marks of the other agents except that they lie in [a,1][a, 1]. So Vi([a,1])≥∣R∣/nV_i([a, 1]) \ge |R|/n while agent ii waits. If agent ii is chosen in line L5, its piece is worth exactly 1/n1/n to it. If it is the last agent, its piece is worth at least 1/n1/n. □\square

Theorem 3 (query count). The protocol makes exactly n(n+1)/2−1n(n+1)/2 - 1 cut queries and no eval queries.

Proof. The round with ∣R∣=r|R| = r makes rr cut queries in line L3 and no other query. The rounds have r=n,n−1,…,2r = n, n - 1, \dots, 2, and line L6 makes no query. So the count is ∑r=2nr=n(n+1)/2−1\sum_{r=2}^{n} r = n(n+1)/2 - 1. ■\blacksquare

Complexity

The round with rr remaining agents makes rr cut queries, for r=n,n−1,…,2r = n, n - 1, \dots, 2. So the protocol makes exactly ∑r=2nr=n(n+1)/2−1\sum_{r=2}^{n} r = n(n+1)/2 - 1 cut queries and no eval queries, which is Θ(n2)\Theta(n^2) on every input. Finding the least mark takes O(r)O(r) comparisons, which the query model does not count. Extra space is O(n)O(n) for the marks.

Properties

  • Connected pieces. Each agent gets one interval, and the cake is cut at n−1n - 1 points.
  • Safe for an honest agent. An agent that calls stop at its true 1/n1/n point, and not before, gets at least 1/n1/n, whatever the others do. If it calls stop too early it gets less than 1/n1/n; if it waits too long, another agent may take a piece that it values at more than 1/n1/n.
  • Envy only toward later pieces. An agent that gets a piece in a round valued every earlier piece at most 1/n1/n, and gets exactly 1/n1/n. So it does not envy the agents that left before it. It may envy agents that leave later, as in the example.
  • Cut queries only. The protocol never asks an eval query. This makes it simple to run with marks on paper: each agent draws one mark per round.
  • Same output as the last diminisher in many cases. On the three-agent example of the last diminisher page, both protocols give the same pieces. They can differ when the last diminisher order makes a different agent the last to trim.

Variants and improvements

  • Last diminisher. The last diminisher of Banach and Knaster passes the piece from agent to agent and lets each one trim it. It mixes eval and cut queries and uses at most n2−1n^2 - 1 queries.
  • Even-Paz. The Even-Paz algorithm also asks each agent for one mark per step, but it cuts at the median mark and recurses on two halves of the agents. It needs O(nlog⁡n)O(n \log n) queries, which is optimal by the Edmonds-Pruhs lower bound.
  • Envy-free moving knives. The Stromquist moving knife uses four knives at once to give three agents an envy-free division with connected pieces. Unlike the Dubins-Spanier knife, it cannot be simulated with finitely many queries.
  • Two agents. For n=2n = 2, the first stop gives one agent a piece worth 1/21/2, and the other agent, which did not stop, values that piece at most 1/21/2. This is a moving-knife form of divide and choose.

When to use it

Use the Dubins-Spanier procedure when you want a proportional division with connected pieces and a simple rule: each agent gives one mark per round, and the least mark wins. It suits a small group and a physical cake or a time line, where marks are easy to draw. For many agents, use the Even-Paz algorithm, which needs O(nlog⁡n)O(n \log n) marks instead of Θ(n2)\Theta(n^2).

Pitfalls

  • Keeping old marks. A mark is a 1/n1/n point from the current left end aa. After a round, aa moves, so every remaining agent must make a new mark. An old mark is worth less than 1/n1/n from the new aa.
  • The largest mark. The piece goes to the least mark. If it went to the largest mark, the other agents could value it at more than 1/n1/n, and the invariant would break.
  • Cut queries that are not the least point. If the valuation is 0 on a stretch, a cut query has many answers. Any answer keeps the guarantee, but the tie rule and the output can change. The implementation returns the least point.
  • Not envy-free. For n≥3n \ge 3 the result can leave agents with envy.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

agtcake.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the algorithmic game theory pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Piecewise-constant cake valuations and a Robertson-Webb query oracle.

The cake is the interval [0, 1]. A valuation is a list of k nonnegative
Fraction densities d[0], ..., d[k - 1]. Density d[j] holds on the segment
[j/k, (j + 1)/k], so that segment has value d[j] / k. A valuation is
normalized when the value of the whole cake is 1, that is, sum(d) = k.

All numbers are Fraction, so every value and every cut point is exact.
This module holds no cake cutting protocol.
"""

from fractions import Fraction
from random import Random
from typing import Optional, Sequence

Valuation = list[Fraction]
Interval = tuple[Fraction, Fraction]

ZERO = Fraction(0)
ONE = Fraction(1)


def normalize(dens: Sequence) -> Valuation:
    """Scale nonnegative densities so that the whole cake has value 1."""
    d = [Fraction(x) for x in dens]
    if not d:
        raise ValueError("a valuation needs at least one segment")
    if any(x < 0 for x in d):
        raise ValueError("densities must be nonnegative")
    total = sum(d)
    if total == 0:
        raise ValueError("densities must not all be zero")
    k = len(d)
    return [x * k / total for x in d]


def _check_point(x: Fraction) -> None:
    if x < 0 or x > 1:
        raise ValueError("a point of the cake must be in [0, 1]")


def value(v: Valuation, a, b) -> Fraction:
    """Return the value of the interval [a, b] under v. Needs 0 <= a <= b <= 1."""
    a, b = Fraction(a), Fraction(b)
    _check_point(a)
    _check_point(b)
    if a > b:
        raise ValueError("value(v, a, b) needs a <= b")
    k = len(v)
    total = ZERO
    j = min(int(a * k), k - 1)
    while j < k:
        lo = Fraction(j, k)
        if lo >= b:
            break
        hi = Fraction(j + 1, k)
        left = a if a > lo else lo
        right = b if b < hi else hi
        if right > left:
            total += v[j] * (right - left)
        j += 1
    return total


def cut(v: Valuation, a, t) -> Optional[Fraction]:
    """Return the least x >= a with value(v, a, x) = t, or None if there is none."""
    a, t = Fraction(a), Fraction(t)
    _check_point(a)
    if t < 0:
        raise ValueError("cut(v, a, t) needs t >= 0")
    if t == 0:
        return a
    k = len(v)
    pos = a
    rest = t
    j = min(int(a * k), k - 1)
    while j < k:
        hi = Fraction(j + 1, k)
        d = v[j]
        if d > 0 and hi > pos:
            here = d * (hi - pos)
            if rest <= here:
                return pos + rest / d
            rest -= here
        if hi > pos:
            pos = hi
        j += 1
    return None


def piece_value(v: Valuation, piece: Sequence[Interval]) -> Fraction:
    """Return the value of a piece, given as a list of intervals (a, b)."""
    return sum((value(v, a, b) for a, b in piece), ZERO)


def random_valuation(rng: Random, k: int, hi: int) -> Valuation:
    """Return a normalized valuation with k segments and integer densities in 0..hi."""
    if k < 1 or hi < 1:
        raise ValueError("random_valuation needs k >= 1 and hi >= 1")
    while True:
        dens = [rng.randint(0, hi) for _ in range(k)]
        if any(dens):
            return normalize(dens)


class Oracle:
    """Answer Robertson-Webb queries for a list of valuations and count them.

    eval_query(i, a, b) returns V_i([a, b]). cut_query(i, a, t) returns the
    least x with V_i([a, x]) = t, or None. The lists evals and cuts hold the
    number of queries of each kind for each agent.
    """

    def __init__(self, valuations: Sequence[Valuation]) -> None:
        self.valuations = [list(v) for v in valuations]
        n = len(self.valuations)
        self.evals = [0] * n
        self.cuts = [0] * n

    @property
    def n(self) -> int:
        return len(self.valuations)

    def eval_query(self, i: int, a, b) -> Fraction:
        self.evals[i] += 1
        return value(self.valuations[i], a, b)

    def cut_query(self, i: int, a, t) -> Optional[Fraction]:
        self.cuts[i] += 1
        return cut(self.valuations[i], a, t)

    def total_evals(self) -> int:
        return sum(self.evals)

    def total_cuts(self) -> int:
        return sum(self.cuts)

    def total(self) -> int:
        return self.total_evals() + self.total_cuts()
dubins_spanier_moving_knife.py 31 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dubins-spanier-moving-knife/. The authors are listed in prov/RTDGDA.jsonl.

from fractions import Fraction

from agtcake import Oracle

Piece = list[tuple[Fraction, Fraction]]


def dubins_spanier(oracle: Oracle) -> dict[int, Piece]:
    """The Dubins-Spanier moving knife, run with cut queries.

    A knife that moves from the left end stops at the first point where
    some remaining agent values the piece to its left at 1/n. That point is
    the least of the agents' 1/n marks, so one cut query per remaining agent
    and round finds it. Ties go to the agent with the smallest index.
    """
    n = oracle.n
    share = Fraction(1, n)
    alloc: dict[int, Piece] = {}
    a = Fraction(0)  # @line L1
    rest = list(range(n))
    while len(rest) > 1:  # @line L2
        marks = {i: oracle.cut_query(i, a, share) for i in rest}  # @line L3
        h = min(rest, key=lambda i: (marks[i], i))  # @line L4
        alloc[h] = [(a, marks[h])]  # @line L5
        rest.remove(h)
        a = marks[h]
    alloc[rest[0]] = [(a, Fraction(1))]  # @line L6
    return alloc
test_dubins_spanier_moving_knife.py 89 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dubins-spanier-moving-knife/. The authors are listed in prov/RTDGDA.jsonl.

import random
from fractions import Fraction

from agtcake import Oracle, normalize, piece_value, random_valuation, value
from dubins_spanier_moving_knife import dubins_spanier

F = Fraction


def check_partition(alloc, n) -> None:
    assert sorted(alloc) == list(range(n))
    assert all(len(alloc[i]) == 1 for i in range(n))
    ivs = sorted(alloc[i][0] for i in range(n))
    assert ivs[0][0] == 0 and ivs[-1][1] == 1
    for (a1, b1), (a2, b2) in zip(ivs, ivs[1:]):
        assert a1 <= b1 == a2 <= b2


def check_knife(vals, alloc) -> None:
    """Replay the knife with the true valuations, independent of the oracle.

    In each round the knife stops at x. Every waiting agent values [a, y] at
    less than 1/n for each y < x (here: at the midpoint of a and x, and just
    left of x), and the receiver values [a, x] at exactly 1/n.
    """
    n = len(vals)
    share = F(1, n)
    owner = {alloc[i][0]: i for i in range(n)}
    waiting = set(range(n))
    for a, x in sorted(owner)[:-1]:
        h = owner[(a, x)]
        assert value(vals[h], a, x) == share
        for j in waiting:
            assert value(vals[j], a, x) <= share
            if x > a:
                for y in (a + (x - a) / 2, x - (x - a) / 10**6):
                    assert value(vals[j], a, y) < share
            # ties go to the smallest index
            if value(vals[j], a, x) == share and x > a:
                assert h <= j
        waiting.remove(h)


def test_example() -> None:
    vals = [normalize(d) for d in ([1, 1, 1, 1], [0, 1, 1, 2], [2, 2, 0, 0], [1, 0, 0, 3])]
    o = Oracle(vals)
    alloc = dubins_spanier(o)
    assert alloc == {
        2: [(0, F(1, 8))],
        0: [(F(1, 8), F(3, 8))],
        1: [(F(3, 8), F(5, 8))],
        3: [(F(5, 8), 1)],
    }
    assert [piece_value(vals[i], alloc[i]) for i in range(4)] == [F(1, 4), F(1, 4), F(1, 4), F(3, 4)]
    assert piece_value(vals[1], alloc[3]) == F(5, 8)  # agent 2 envies agent 4
    assert o.cuts == [2, 3, 1, 3] and o.total_evals() == 0
    assert o.total() == 4 * 5 // 2 - 1
    check_knife(vals, alloc)


def test_random_valuations() -> None:
    rng = random.Random(99)
    for _ in range(150):
        n = rng.randint(1, 5)
        vals = [random_valuation(rng, rng.randint(1, 8), 6) for _ in range(n)]
        o = Oracle(vals)
        alloc = dubins_spanier(o)
        check_partition(alloc, n)
        check_knife(vals, alloc)
        for i in range(n):
            assert piece_value(vals[i], alloc[i]) >= F(1, n)
        assert o.total_evals() == 0
        assert o.total_cuts() == n * (n + 1) // 2 - 1


def test_identical_valuations() -> None:
    rng = random.Random(8)
    for n in range(1, 6):
        v = random_valuation(rng, 7, 3)
        alloc = dubins_spanier(Oracle([v] * n))
        check_partition(alloc, n)
        for i in range(n):
            assert piece_value(v, alloc[i]) == F(1, n)
        # all marks tie in each round, so agent 0 stops first, then agent 1, ...
        starts = [alloc[i][0][0] for i in range(n)]
        assert starts == sorted(starts)

History

Dubins and Spanier (1961) described the moving knife in "How to cut a cake fairly", in the American Mathematical Monthly. The same paper proves the existence of divisions with stronger properties, such as divisions in which each agent values each piece at exactly 1/n1/n. The protocol gives the same guarantee as the earlier last diminisher of Banach and Knaster, which Steinhaus published in 1948. In the Robertson-Webb model, its Θ(n2)\Theta(n^2) cut queries were later improved to O(nlog⁡n)O(n \log n) by Even and Paz (1984).

References

  1. Lester E. Dubins and Edwin H. Spanier, How to cut a cake fairly, American Mathematical Monthly 68(1) (1961), 1-17, the moving-knife method for n people, and the existence results for fair divisions
  2. Steven J. Brams and Alan D. Taylor, Fair Division, From Cake-Cutting to Dispute Resolution, Cambridge University Press, 1996, Chapter 2, Proportionality for n > 2, the divisible case (from p. 30)
  3. Felix Brandt, Vincent Conitzer, Ulle Endriss, Jerome Lang and Ariel D. Procaccia (eds.), Handbook of Computational Social Choice, Cambridge University Press, 2016, Chapter 13, Ariel D. Procaccia, Cake Cutting Algorithms, Section 13.3, classic algorithms (from p. 313)

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • a scene preset for the example