Algorithm Search⌘K

Algorithmcore

Even-Paz algorithm

Also called Even-Paz divide and conquer.

A proportional cake cutting protocol that cuts at the median of the agents' half-value marks and recurses on each half, with O(n log n) queries.

Time
Θ(n log n) worst
Space
Θ(n) extra
Where
n = the number of agents
Properties
deterministicofflinerecursive

The Even-Paz algorithm is a divide and conquer protocol for proportional division of a cake among nn agents. Each agent marks the point that splits the current piece in the ratio ⌊n/2⌋:⌈n/2⌉\lfloor n/2 \rfloor : \lceil n/2 \rceil by its own measure. The cake is cut at the median mark: the agents with the smaller marks share the left part, the others share the right part, and each group repeats the method. Each agent gets a connected piece worth at least 1/n1/n to it. The protocol uses O(nlog⁡n)O(n \log n) queries in the Robertson-Webb query model, and the Edmonds-Pruhs lower bound shows that no deterministic protocol does better.

In plain words

A large group of friends shares a cake. Instead of cutting one fair slice at a time, they split the group in two. Each friend draws a line where the cake splits into a left part that is fair for half of the group and a right part that is fair for the other half, as that friend sees it. The cake is cut at the middle line of all the lines.

The friends whose lines are left of the cut think the left part is big enough for half the group, so they take it. The other friends think the same of the right part. Each half then does the same thing on its own part, until each friend is alone with a piece. Because the group halves each time, each friend draws only a few lines.

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: Evali(a,b)\mathrm{Eval}_i(a, b) returns Vi([a,b])V_i([a, b]), and 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

The recursive call gets a set SS of kk agents and an interval [a,b][a, b]. It guarantees that each agent i∈Si \in S gets at least Vi([a,b])/kV_i([a, b])/k. The first call is \textsc{Even-Paz}(\{1, \dots, n\}, [0, 1]), where Vi([0,1])=1V_i([0, 1]) = 1 is known and needs no query.

  1. EVEN-PAZ(S, [a, b]) ▷ each i in S gets at least V_i([a, b]) / |S|
  2. 1if |S| = 1 then give [a, b] to the agent of S; return
  3. 2k ← |S|; k1 ← ⌊k/2⌋
  4. 3for each agent i of S do
  5. 4w_i ← EVAL_i(a, b) ▷ no query at the root, where w_i = 1
  6. 5m_i ← CUT_i(a, w_i · k1/k) ▷ [a, m_i] is worth k1/k of [a, b] to i
  7. 6sort S by (m_i, i)
  8. 7x ← the k1-th mark; L ← the first k1 agents; R ← the other k − k1 agents
  9. 8EVEN-PAZ(L, [a, x])
  10. 9EVEN-PAZ(R, [x, b])

The cut point xx is a median of the marks: k1k_1 marks are at most xx, and the other k−k1k - k_1 marks are at least xx. Ties go to the agent with the smaller index, so the split of SS into LL and RR is well defined. For k=2k = 2 the call is a form of divide and choose in which both agents mark their half points and the cake is cut at the smaller mark.

Example

Split [0,1][0, 1] into four equal segments, and let the densities 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.

call agents wiw_i marks mim_i cut xx left group right group
[0,1][0, 1] 1, 2, 3, 4 1, 1, 1, 1 1/2,3/4,1/4,5/61/2, 3/4, 1/4, 5/6 1/21/2 3, 1 2, 4
[0,1/2][0, 1/2] 1, 3 1/2,11/2, 1 1/4,1/41/4, 1/4 1/41/4 1 3
[1/2,1][1/2, 1] 2, 4 3/4,3/43/4, 3/4 13/16,7/813/16, 7/8 13/1613/16 2 4

In the second call, both marks are 1/41/4, and the tie goes to agent 1. The pieces are [0,1/4][0, 1/4] for agent 1, [1/4,1/2][1/4, 1/2] for agent 3, [1/2,13/16][1/2, 13/16] for agent 2 and [13/16,1][13/16, 1] for agent 4. Their values for the owners are 1/41/4, 1/21/2, 3/83/8 and 9/169/16, all at least 1/41/4. The run makes 8 cut queries and 4 eval queries, 12 in total. The result is not envy-free: agent 1 values the piece of agent 2 at 5/165/16.

Correctness

Claim. A call on SS and [a,b][a, b] gives each agent i∈Si \in S a piece worth at least Vi([a,b])/∣S∣V_i([a, b])/|S| to it.

The proof is by induction on k=∣S∣k = |S|. For k=1k = 1 the agent gets all of [a,b][a, b]. For k≥2k \ge 2, let w=Vi([a,b])w = V_i([a, b]). If i∈Li \in L, then mi≤xm_i \le x, so Vi([a,x])≥Vi([a,mi])=wk1/kV_i([a, x]) \ge V_i([a, m_i]) = w k_1/k, and the call on LL gives ii at least (wk1/k)/k1=w/k(w k_1 / k)/k_1 = w/k. If i∈Ri \in R, then mi≥xm_i \ge x, so Vi([a,x])≤wk1/kV_i([a, x]) \le w k_1/k and Vi([x,b])≥w(k−k1)/kV_i([x, b]) \ge w (k - k_1)/k; the call on RR gives ii at least w/kw/k. At the root, w=1w = 1 and k=nk = n, so each agent gets at least 1/n1/n. The full proof is in proofs/correctness.md.

Proof: The Even-Paz algorithm is proportional and uses at most 2n ceil(lg n) - n 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 mm has Vi([a,m])=tV_i([a, m]) = t. Single points have value 0. We refer to the lines L1 to L9 of the page, and we write L=⌈lg⁡n⌉L = \lceil \lg n \rceil.

Lemma 1 (the cut queries have answers). In a call on SS and [a,b][a, b], the query of line L5 asks for wik1/k≤wi=Vi([a,b])w_i k_1/k \le w_i = V_i([a, b]), and its answer mim_i lies in [a,b][a, b].

Proof. k1/k≤1k_1/k \le 1, so the asked value is at most Vi([a,b])≤Vi([a,1])V_i([a, b]) \le V_i([a, 1]), and an answer exists. The least answer is at most bb, because Vi([a,b])≥wik1/kV_i([a, b]) \ge w_i k_1/k. □\square

So the cut point xx of line L7 lies in [a,b][a, b], and the calls of lines L8 and L9 are on intervals inside [a,b][a, b] that meet only at xx.

Lemma 2 (the split). After the sort of line L6, every agent i∈Li \in L has mi≤xm_i \le x and every agent i∈Ri \in R has mi≥xm_i \ge x, and ∣L∣=k1≥1|L| = k_1 \ge 1, ∣R∣=k−k1≥1|R| = k - k_1 \ge 1.

Proof. The sort is by mim_i first, and xx is the mark of the k1k_1-th agent in sorted order. For k≥2k \ge 2, k1=⌊k/2⌋≥1k_1 = \lfloor k/2 \rfloor \ge 1 and k−k1=⌈k/2⌉≥1k - k_1 = \lceil k/2 \rceil \ge 1. □\square

Theorem 1 (each agent gets its share of the interval). A call on a set SS of k≥1k \ge 1 agents and an interval [a,b][a, b] gives the agents of SS disjoint intervals that cover [a,b][a, b], and agent i∈Si \in S gets an interval worth at least Vi([a,b])/kV_i([a, b])/k to it.

Proof. By strong induction on kk. For k=1k = 1, line L1 gives all of [a,b][a, b] to the one agent, worth Vi([a,b])V_i([a, b]).

Let k≥2k \ge 2 and w=Vi([a,b])w = V_i([a, b]) for an agent i∈Si \in S. By Lemma 2 the two recursive calls have fewer than kk agents, so the induction hypothesis applies to them, and together they cover [a,x]∪[x,b]=[a,b][a, x] \cup [x, b] = [a, b].

If i∈Li \in L, then mi≤xm_i \le x, and monotonicity gives Vi([a,x])≥Vi([a,mi])=wk1/kV_i([a, x]) \ge V_i([a, m_i]) = w k_1/k. The call on LL gives agent ii at least

Vi([a,x])k1≥wk1/kk1=wk.\frac{V_i([a, x])}{k_1} \ge \frac{w k_1 / k}{k_1} = \frac{w}{k}.

If i∈Ri \in R, then mi≥xm_i \ge x, so Vi([a,x])≤Vi([a,mi])=wk1/kV_i([a, x]) \le V_i([a, m_i]) = w k_1/k, and additivity gives Vi([x,b])=w−Vi([a,x])≥w(k−k1)/kV_i([x, b]) = w - V_i([a, x]) \ge w (k - k_1)/k. The call on RR gives agent ii at least

Vi([x,b])k−k1≥w(k−k1)/kk−k1=wk.□\frac{V_i([x, b])}{k - k_1} \ge \frac{w (k - k_1)/k}{k - k_1} = \frac{w}{k}. \qquad \square

Corollary (proportional). The first call has S={1,…,n}S = \{1, \dots, n\}, [a,b]=[0,1][a, b] = [0, 1] and Vi([0,1])=1V_i([0, 1]) = 1, so each agent gets one interval worth at least 1/n1/n, and the intervals partition [0,1][0, 1]. The root uses wi=1w_i = 1 without a query; this is correct because the valuations are normalized.

Remark (safe for an honest agent). The proof for agent ii uses only the answers of agent ii and the fact that xx is chosen so that agent ii lands on the side of xx that its own mark selects. It uses nothing about the answers of other agents, except that their marks lie in [a,b][a, b]. So an agent that answers by ViV_i gets at least 1/n1/n whatever the others answer.

Lemma 3 (the shape of the recursion). For n≥2n \ge 2, the tree of calls has nn leaves, every internal call has two children, and every leaf has depth L−1L - 1 or LL. Exactly 2n−2L2n - 2^L leaves have depth LL, and 2L−n2^L - n leaves have depth L−1L - 1.

Proof. The sizes of the calls at depth dd are ⌊n/2d⌋\lfloor n/2^d \rfloor or ⌈n/2d⌉\lceil n/2^d \rceil, by induction on dd: halving ⌊m⌋\lfloor m \rfloor or ⌈m⌉\lceil m \rceil into floor and ceiling parts gives ⌊m/2⌋\lfloor m/2 \rfloor or ⌈m/2⌉\lceil m/2 \rceil. Since 2L−1<n≤2L2^{L-1} < n \le 2^L, every call at depth d≤L−2d \le L - 2 has size at least ⌊n/2L−2⌋≥2\lfloor n/2^{L-2} \rfloor \ge 2, so it is internal. Hence depth L−1L - 1 has 2L−12^{L-1} calls, each of size ⌈n/2L−1⌉≤2\lceil n/2^{L-1} \rceil \le 2 or ⌊n/2L−1⌋≥1\lfloor n/2^{L-1} \rfloor \ge 1, so of size 1 or 2. Let cc be the number of size 1. Then c+2(2L−1−c)=nc + 2(2^{L-1} - c) = n, so c=2L−nc = 2^L - n leaves have depth L−1L - 1, and the 2L−1−c2^{L-1} - c calls of size 2 have 2(2L−1−c)=2n−2L2(2^{L-1} - c) = 2n - 2^L children of size 1 at depth LL. □\square

Theorem 2 (query count). For n≥2n \ge 2, the protocol makes nL−2L+n≤nLnL - 2^L + n \le nL cut queries and nL−2LnL - 2^L eval queries, so

2nL−2L+1+n≤2nL−n2nL - 2^{L+1} + n \le 2nL - n

queries in total, with equality when nn is a power of 2. For n=1n = 1 it makes no query.

Proof. A call on k≥2k \ge 2 agents asks each of its agents one cut query, and one eval query unless it is the root. So agent ii gets one cut query for each internal call on the path from the root to its leaf, that is, as many cut queries as the depth of its leaf, and one eval fewer. By Lemma 3 the sum of the depths is

L(2n−2L)+(L−1)(2L−n)=nL−2L+n.L(2n - 2^L) + (L - 1)(2^L - n) = nL - 2^L + n.

This is the count of cut queries. It is at most nLnL because n≤2Ln \le 2^L. The eval queries number nn fewer, nL−2LnL - 2^L. The total is 2nL−2L+1+n2nL - 2^{L+1} + n, and 2L+1≥2n2^{L+1} \ge 2n gives the bound 2nL−n2nL - n, with equality exactly when n=2Ln = 2^L. For n=1n = 1, line L1 returns at once. ■\blacksquare

Complexity

A call on k≥2k \ge 2 agents makes kk cut queries and kk eval queries (none at the root), and then calls itself on ⌊k/2⌋\lfloor k/2 \rfloor and ⌈k/2⌉\lceil k/2 \rceil agents. With T(1)=0T(1) = 0 and T(k)=2k+T(⌊k/2⌋)+T(⌈k/2⌉)T(k) = 2k + T(\lfloor k/2 \rfloor) + T(\lceil k/2 \rceil), the protocol makes T(n)−nT(n) - n queries, because the root skips its nn evals. The recursion has depth ⌈lg⁡n⌉\lceil \lg n \rceil, and each level asks each agent at most one cut and one eval. A closed form is

T(n)−n=2n⌈lg⁡n⌉−2⌈lg⁡n⌉+1+n≤2n⌈lg⁡n⌉−n,T(n) - n = 2n \lceil \lg n \rceil - 2^{\lceil \lg n \rceil + 1} + n \le 2n \lceil \lg n \rceil - n,

with equality when nn is a power of 2. For n=4n = 4 this is 12, as in the example. The cut queries number at most n⌈lg⁡n⌉n \lceil \lg n \rceil. So the cost is Θ(nlog⁡n)\Theta(n \log n) on every input, the same shape as the cost of merge sort. The sort of line L6 takes O(klog⁡k)O(k \log k) comparisons, which the query model does not count, and the extra space is O(n)O(n) for the marks and the recursion.

Properties

  • Connected pieces. Each call cuts its interval at one point, so each agent gets one interval.
  • Safe for an honest agent. The guarantee of 1/n1/n for agent ii uses only the answers of agent ii and the choice of xx as a median. An agent that answers by its true valuation gets at least 1/n1/n whatever the others answer.
  • Optimal query count. The Edmonds-Pruhs lower bound shows that every deterministic proportional protocol needs Ω(nlog⁡n)\Omega(n \log n) queries, even with pieces that are unions of intervals. Woeginger and Sgall had shown this before for connected pieces.
  • Not envy-free, not equitable. The example shows envy, and the values of the agents differ.
  • Balanced recursion. The split ⌊k/2⌋:⌈k/2⌉\lfloor k/2 \rfloor : \lceil k/2 \rceil keeps the depth at ⌈lg⁡n⌉\lceil \lg n \rceil. Any split k1:k−k1k_1 : k - k_1 with 1≤k1<k1 \le k_1 < k keeps the guarantee, but an unbalanced split costs more queries. The split 1:k−11 : k - 1 gives a protocol much like the Dubins-Spanier moving knife, with Θ(n2)\Theta(n^2) queries.

Variants and improvements

  • No evals. The evals of line L4 can be dropped. Give each agent a budget BiB_i with Bi≤Vi([a,b])B_i \le V_i([a, b]), starting at Bi=1B_i = 1, and mark at Cuti(a,Bik1/k)\mathrm{Cut}_i(a, B_i k_1/k). An agent in LL goes on with budget Bik1/kB_i k_1/k, and an agent in RR with budget Bi(k−k1)/kB_i (k - k_1)/k, and the same induction shows that each agent gets at least Bi/∣S∣B_i/|S|. This version uses at most n⌈lg⁡n⌉n \lceil \lg n \rceil cut queries and no eval query.
  • Randomized version. Even and Paz also gave a randomized protocol with O(n)O(n) expected cut queries. Edmonds and Pruhs showed that randomized protocols still need Ω(nlog⁡n)\Omega(n \log n) queries when the answers are approximate.
  • Linear cuts. A 2026 preprint by Arndt, Moseley, Im and Pruhs (arXiv 2606.07238) gives a deterministic protocol with O(n)O(n) cut queries and O(n2)O(n^2) eval queries. It does not beat Ω(nlog⁡n)\Omega(n \log n) queries in total, but it shows that cuts alone need not grow as nlog⁡nn \log n.
  • Unequal shares. When agent ii is entitled to a share wiw_i instead of 1/n1/n, the same idea works with splits by entitlement instead of by count. The query complexity of this case was studied by Cseh and Fleiner.
  • Simpler quadratic protocols. The last diminisher and the Dubins-Spanier procedure use Θ(n2)\Theta(n^2) queries but give one piece per round, which is easier to run by hand.

When to use it

Use Even-Paz when nn is large and queries are costly, for example when each query is a question to a person or a call to a slow model of preferences. It gives connected pieces and the best possible order of queries for deterministic proportional division. If envy matters, it is not enough: use an envy-free protocol such as Selfridge-Conway for three agents.

Pitfalls

  • Marks of the wrong size. Line L5 asks for a fraction k1/kk_1/k of the value of the current interval [a,b][a, b], not of the whole cake. With the whole cake as the base, the induction fails.
  • Odd kk. For odd kk the two groups differ in size. The mark must use k1/kk_1/k with k1=⌊k/2⌋k_1 = \lfloor k/2 \rfloor, the size of the left group. A mark at value 1/21/2 breaks the guarantee for the larger group.
  • Ties in the marks. When several marks equal xx, the agents with these marks must be split by a fixed rule so that exactly k1k_1 agents go left. Each agent with mi=xm_i = x is safe in either group.
  • Recursion on the wrong side. The left group must get [a,x][a, x] and the right group [x,b][x, b], with xx the k1k_1-th mark in sorted order. Swapping them gives no guarantee.

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()
even_paz_algorithm.py 57 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/even-paz-algorithm/. The authors are listed in prov/E1V4HN.jsonl.

from fractions import Fraction
from typing import Optional

from agtcake import Oracle

Piece = list[tuple[Fraction, Fraction]]


def even_paz(oracle: Oracle) -> dict[int, Piece]:
    """Even-Paz divide and conquer for the n agents of the oracle.

    Each agent gets one interval, worth at least 1/n to it.
    """
    alloc: dict[int, Piece] = {}
    agents = list(range(oracle.n))
    whole = {i: Fraction(1) for i in agents}  # V_i([0, 1]) = 1 needs no query
    _even_paz(oracle, agents, Fraction(0), Fraction(1), whole, alloc)
    return alloc


def _even_paz(
    oracle: Oracle,
    agents: list[int],
    a: Fraction,
    b: Fraction,
    known: Optional[dict[int, Fraction]],
    alloc: dict[int, Piece],
) -> None:
    """Divide [a, b] among agents. known holds V_i([a, b]) when it is known."""
    k = len(agents)
    if k == 1:  # @line L1
        alloc[agents[0]] = [(a, b)]
        return
    k1 = k // 2  # @line L2
    worth: dict[int, Fraction] = {}
    marks: dict[int, Fraction] = {}
    for i in agents:  # @line L3
        w = known[i] if known is not None else oracle.eval_query(i, a, b)  # @line L4
        worth[i] = w
        marks[i] = oracle.cut_query(i, a, w * k1 / k)  # @line L5
    order = sorted(agents, key=lambda i: (marks[i], i))  # @line L6
    left, right = order[:k1], order[k1:]
    x = marks[order[k1 - 1]]  # @line L7
    _even_paz(oracle, left, a, x, None, alloc)  # @line L8
    _even_paz(oracle, right, x, b, None, alloc)  # @line L9


def query_count(n: int) -> int:
    """The exact number of queries of even_paz on n agents (cuts plus evals)."""

    def t(k: int) -> int:
        return 0 if k <= 1 else 2 * k + t(k // 2) + t(k - k // 2)

    return t(n) - n if n > 1 else 0
test_even_paz_algorithm.py 85 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/even-paz-algorithm/. The authors are listed in prov/E1V4HN.jsonl.

import random
from fractions import Fraction

from agtcake import Oracle, normalize, piece_value, random_valuation
from even_paz_algorithm import even_paz, query_count

F = Fraction


def ceil_lg(n: int) -> int:
    return (n - 1).bit_length()


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 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 = even_paz(o)
    assert alloc == {
        0: [(0, F(1, 4))],
        2: [(F(1, 4), F(1, 2))],
        1: [(F(1, 2), F(13, 16))],
        3: [(F(13, 16), 1)],
    }
    assert [piece_value(vals[i], alloc[i]) for i in range(4)] == [F(1, 4), F(3, 8), F(1, 2), F(9, 16)]
    assert o.cuts == [2, 2, 2, 2] and o.evals == [1, 1, 1, 1]
    assert o.total() == query_count(4) == 12


def test_query_count_formula() -> None:
    for n in range(2, 65):
        L = ceil_lg(n)
        assert query_count(n) == 2 * n * L - 2 ** (L + 1) + n
        assert query_count(n) <= 2 * n * L - n
        if n == 2**L:
            assert query_count(n) == 2 * n * L - n
    assert query_count(1) == 0


def test_random_valuations() -> None:
    rng = random.Random(31337)
    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 = even_paz(o)
        check_partition(alloc, n)
        for i in range(n):
            assert piece_value(vals[i], alloc[i]) >= F(1, n)
        assert o.total() == query_count(n)
        assert o.total_cuts() <= n * ceil_lg(n)
        assert o.total_evals() == query_count(n) - o.total_cuts()


def test_more_agents_few_segments() -> None:
    rng = random.Random(4)
    for n in (6, 7, 8):
        vals = [random_valuation(rng, 4, 3) for _ in range(n)]
        o = Oracle(vals)
        alloc = even_paz(o)
        check_partition(alloc, n)
        for i in range(n):
            assert piece_value(vals[i], alloc[i]) >= F(1, n)
        assert o.total() == query_count(n)


def test_identical_valuations() -> None:
    rng = random.Random(6)
    for n in range(1, 6):
        v = random_valuation(rng, 6, 4)
        alloc = even_paz(Oracle([v] * n))
        check_partition(alloc, n)
        for i in range(n):
            assert piece_value(v, alloc[i]) == F(1, n)

History

Even and Paz published the protocol in 1984 in "A note on cake cutting", in Discrete Applied Mathematics. It improved the Θ(n2)\Theta(n^2) queries of the last diminisher (Steinhaus, 1948) and of the Dubins-Spanier procedure (1961) to O(nlog⁡n)O(n \log n). The same paper gave a randomized protocol with O(n)O(n) expected cuts. The question whether O(nlog⁡n)O(n \log n) is optimal stayed open until Woeginger and Sgall (2007) proved Ω(nlog⁡n)\Omega(n \log n) for connected pieces and Edmonds and Pruhs (SODA 2006; ACM Transactions on Algorithms 2011) proved it for all deterministic protocols.

References

  1. Shimon Even and Azaria Paz, A note on cake cutting, Discrete Applied Mathematics 7(3) (1984), pp. 285-296 (the divide and conquer protocol with O(n log n) cuts, and the randomized protocol with O(n) expected cuts)
  2. Jeff Edmonds and Kirk Pruhs, Cake cutting really is not a piece of cake, ACM Transactions on Algorithms 7(4) (2011), Article 51; Section 2, Theorem 4 (the matching lower bound for deterministic protocols)
  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), and Section 13.4, complexity of cake cutting (from p. 316)

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