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.
- Solves
- Cake cutting problem
- Time
- Θ(n^2) worst
- Space
- Θ(n) extra
- Where
- n = the number of agents
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
The Dubins-Spanier moving knife is a protocol that gives each of agents a connected piece of a cake worth at least 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 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 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 . Agent has a nonnegative, additive and nonatomic valuation with . The protocol must output disjoint intervals that cover , with for every . It learns the valuations only by queries. Here it needs only the cut query: returns the least point with .
The algorithm
A continuous knife is not a finite protocol, but this one is easy to simulate. When the knife starts at , agent would call stop at its mark . The knife therefore stops at the least mark. So the protocol asks every remaining agent for its mark and takes the least one.
DUBINS-SPANIER(n)- 1
a ← 0; R ← {1, 2, …, n} - 2
while |R| > 1 do - 3
for each agent i of R do m_i ← CUT_i(a, 1/n) ▷ where agent i would call stop - 4
h ← the agent of R with the least m_i ▷ ties go to the smallest index - 5
give [a, m_h] to h; remove h from R; a ← m_h - 6
give [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 into four equal segments, and let the densities on them be for agent 1, for agent 2, for agent 3 and for agent 4. Each list sums to 4, so each agent values the whole cake at 1. Here and .
| round | marks of the remaining agents | least mark | piece | |
|---|---|---|---|---|
| 1 | 0 | , , , | agent 3 | |
| 2 | , , | agent 1 | ||
| 3 | , | agent 2 | ||
| agent 4 |
Agents 3, 1 and 2 get exactly , and agent 4 gets . The run makes cut queries and no eval queries. The result is proportional but not envy-free: agent 2 values the piece of agent 4 at , and agent 3 values the piece of agent 1 at .
Correctness
Invariant. At the start of each round, every agent in has .
It holds at the start with and . In a round, the receiver has the least mark, so every other agent of has and . Hence , which is the invariant for the next round. Each receiver in line L5 gets exactly , and the last agent gets at least by the invariant with . The cut queries have answers because each agent in values at least . 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 , and agent has a nonnegative, additive and nonatomic valuation with . For , the map is continuous and nondecreasing on , since is nonatomic. So has an answer whenever , and the least answer has . 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 , and let each agent call stop at the first point with . Then the knife stops at , where is the least answer.
Proof. By continuity, the first point with is the least with , which is . The knife stops at the first call, so at .
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 has .
Proof. By induction on the rounds. The first time, , and . Suppose the invariant holds at the start of a round. Each cut query of line L3 asks for , so it has an answer. Let be the agent of line L4. For each , we have , so monotonicity gives . Additivity then gives
Line L5 sets and removes , so the invariant holds for the new .
Theorem 1 (proportional). The output is a partition of into intervals, and for every agent .
Proof. Each round removes one agent, so the loop runs times. The successive left ends satisfy , because a cut from returns a point at least . The pieces of line L5 and the piece of line L6 cover and meet only at end points. Each agent of line L5 gets . The last agent gets by Lemma 2 with .
Theorem 2 (safe for an honest agent). If agent answers by , then , whatever points the other agents give as marks.
Proof. The proof of Lemma 2 for the single agent uses only its own mark and the choice of the least mark in line L4: if agent is not chosen, some mark was chosen, so . This needs nothing about the marks of the other agents except that they lie in . So while agent waits. If agent is chosen in line L5, its piece is worth exactly to it. If it is the last agent, its piece is worth at least .
Theorem 3 (query count). The protocol makes exactly cut queries and no eval queries.
Proof. The round with makes cut queries in line L3 and no other query. The rounds have , and line L6 makes no query. So the count is .
Complexity
The round with remaining agents makes cut queries, for . So the protocol makes exactly cut queries and no eval queries, which is on every input. Finding the least mark takes comparisons, which the query model does not count. Extra space is for the marks.
Properties
- Connected pieces. Each agent gets one interval, and the cake is cut at points.
- Safe for an honest agent. An agent that calls stop at its true point, and not before, gets at least , whatever the others do. If it calls stop too early it gets less than ; if it waits too long, another agent may take a piece that it values at more than .
- Envy only toward later pieces. An agent that gets a piece in a round valued every earlier piece at most , and gets exactly . 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 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 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 , the first stop gives one agent a piece worth , and the other agent, which did not stop, values that piece at most . 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 marks instead of .
Pitfalls
- Keeping old marks. A mark is a point from the current left end . After a round, moves, so every remaining agent must make a new mark. An old mark is worth less than from the new .
- 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 , 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 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.
# 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 . 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 cut queries were later improved to by Even and Paz (1984).
References
- 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
- 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)
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag RTDGDA Edit this page History Report an error Markdown