Algorithm Search⌘K

Algorithmresearch

Jain-Vazirani cost sharing for Steiner trees

Also called primal-dual cost sharing for Steiner trees.

A cross-monotonic cost-sharing method for Steiner trees from a primal-dual algorithm. The shares pay for a spanning tree of the metric closure and are at most twice the optimal cost.

Time
O(N^3 + k^2 log k) worst
Space
O(N^2) extra
Where
N = the number of vertices of the graph; k = the number of terminals
Properties
deterministicexactofflineiterative
Origin
Kamal Jain, Vijay V. Vazirani, 2001

Jain-Vazirani cost sharing splits the cost of a Steiner tree among the terminals that must be connected to a root. The cost of serving a set of terminals is the cost of an optimal Steiner tree for them, which is NP-hard to compute, so exact budget balance is out of reach. Jain and Vazirani (2001) took a primal-dual algorithm, in which the components of terminals grow a dual value over time, and charged each terminal its part of the dual of its component. The shares pay for a minimum spanning tree of the terminals and the root in the shortest path metric, so they cover a tree that serves the set and are at most twice the optimal cost. They are cross-monotonic: a terminal never pays more when more terminals join. Run inside the Moulin mechanism, they give a group strategyproof mechanism for multicast and network design.

In plain words

A server must send a stream to some users through a network, and each link has a cost. The users who join must pay for the links. Think of a clock that runs from zero. At each moment, users who are close enough to each other form a group, and a group joins the server when it is close enough to it. Until its group reaches the server, each user pays a small amount for every tick of the clock, split equally inside the group. So a user in a big group pays less per tick, and a group near the server stops paying early. The total paid is enough to build a network that reaches all users, and at most twice the cheapest one. When more users join, groups form sooner and grow larger, so nobody pays more.

The problem

The input is a connected undirected graph GG with NN vertices and nonnegative edge costs, a root rr, and a set SS of kk terminals, the players. For a set T⊆ST \subseteq S, the cost C(T)C(T) is the cost of a cheapest connected subgraph of GG that contains T∪{r}T \cup \{r\}, the optimal Steiner tree. The output is a share ξ(i,T)\xi(i, T) for each T⊆ST \subseteq S and each i∈Ti \in T, computed for one given TT at a time. The goals are:

  • Cross-monotonicity. ξ(i,T)≥ξ(i,T′)\xi(i, T) \ge \xi(i, T') whenever i∈T⊆T′i \in T \subseteq T'.
  • Approximate budget balance. C(T)≤∑i∈Tξ(i,T)≤β C(T)C(T) \le \sum_{i \in T} \xi(i, T) \le \beta\, C(T) for a small β\beta.

This page uses the form of β\beta-budget balance in which the shares cover the cost and are at most β\beta times it, and the method here has β=2\beta = 2. Jain and Vazirani state the result in the other form, 12C(T)≤∑iξ(i,T)≤C(T)\frac{1}{2} C(T) \le \sum_i \xi(i, T) \le C(T), which is the same method with all shares divided by 2. Exact budget balance would need ∑iξ(i,T)=C(T)\sum_i \xi(i, T) = C(T), and computing C(T)C(T) is NP-hard.

The algorithm

  1. JV-SHARES(G, r, S)
  2. 1d ← shortest path costs of G between the points of P = S ∪ {r}
  3. 2E ← the pairs {u, v} of P, sorted by d(u, v)
  4. 3each point of P is its own component; ξ_i ← 0 for i ∈ S; t ← 0
  5. 4for each {u, v} in E with u and v in different components:
  6. 5for each component K without r: ξ_i ← ξ_i + (d(u, v) - t)/|K| for i ∈ K
  7. 6t ← d(u, v); merge the components of u and v
  8. 7return ξ

Line L1 builds the metric closure of GG on the terminals and the root, for example with Floyd-Warshall. Lines L2 to L6 run Kruskal's algorithm on the complete graph on PP, and use the merge costs as a clock. Between two merges, the components do not change. Line L5 charges each component that has not reached the root for the time since the last merge, split equally among its members. Line L6 moves the clock and merges. Once all points are in the component of rr, nothing more is charged. The tree that Kruskal's algorithm builds, with each closure edge replaced by a shortest path in GG, is the network that the shares pay for.

This is the threshold form of the method. Jain and Vazirani describe it as a primal-dual algorithm on the bidirected graph on PP, with the cut relaxation used by Edmonds for arborescences. Each component without rr is an active set that raises its dual at rate 1, and its terminals split the increase equally. An arc into an active component becomes tight when the dual of the component reaches its cost, which happens exactly when the pair enters the graph of pairs with d(u,v)≤td(u, v) \le t. The proof file shows that both views give the same shares.

Example

The root is rr and the terminals are aa, bb and cc. One more vertex ss is not a terminal. The edges are rs=4r s = 4, sa=1s a = 1, sb=1s b = 1, sc=2s c = 2 and rc=5r c = 5. The metric closure on P={r,a,b,c}P = \{r, a, b, c\} has d(a,b)=2d(a, b) = 2, d(a,c)=d(b,c)=3d(a, c) = d(b, c) = 3 and d(r,a)=d(r,b)=d(r,c)=5d(r, a) = d(r, b) = d(r, c) = 5.

time components without rr charge per unit of time ξa\xi_a, ξb\xi_b, ξc\xi_c at the end
0 to 2 {a}, {b}, {c} 1 each 2, 2, 2
2 to 3 {a, b}, {c} 1/2, 1/2, 1 5/2, 5/2, 3
3 to 5 {a, b, c} 1/3 each 19/6, 19/6, 11/3

At time 5 the component reaches rr and the charges stop. The shares are (19/6,19/6,11/3)(19/6, 19/6, 11/3), and they sum to 10, the cost of a minimum spanning tree on PP with the costs dd: for example abab, acac and rara with costs 2, 3 and 5. With the shortest paths in GG, this tree uses the edges rsrs, sasa, sbsb and scsc, of total cost 8, which is also the optimal Steiner tree. So here the shares are 10, between the optimal cost 8 and twice it.

Cross-monotonicity shows in the shares of aa for the sets that contain it.

set shares sum optimal cost
{a} 5 5 5
{a, b} 7/2, 7/2 7 6
{a, c} 4, 4 8 7
{a, b, c} 19/6, 19/6, 11/3 10 8

The share of aa falls from 5 to 7/27/2 or 4, and then to 19/619/6, as more terminals join.

Correctness

The file proofs/correctness.md gives the full proofs. Let GtG_t be the graph on PP with the pairs of cost at most tt, and Kt(i)K_t(i) the component of ii in it. Then the share of terminal ii is the integral over tt of 1/∣Kt(i)∣1/|K_t(i)|, over the times at which Kt(i)K_t(i) does not contain rr.

  • The sum. Each component without rr pays at total rate 1, so the sum of the shares is the integral of the number of components of GtG_t minus 1. This is the sum of the Kruskal merge costs, the cost of a minimum spanning tree on PP.
  • Budget. A minimum spanning tree on PP maps to a connected subgraph of GG through shortest paths, so it costs at least the optimal Steiner tree. Doubling an optimal Steiner tree and shortcutting its Euler tour gives a spanning path of PP of cost at most twice the optimum, so the minimum spanning tree costs at most twice the optimum.
  • Cross-monotonicity. Adding terminals does not change the metric. So GtG_t for a smaller set is an induced subgraph of GtG_t for a larger set, each component only grows, and each component reaches rr no later. The integrand, and so the share, can only fall.
Proof: The Jain-Vazirani shares are cross-monotonic, recover between the optimal Steiner cost and twice it, and match the primal-dual algorithmfull

Setting. GG is a connected undirected graph with NN vertices and edge costs ce≥0c_e \ge 0. The vertex rr is the root and SS is a set of kk terminals, the players, with r∉Sr \notin S. Let dd be the shortest path metric of GG, and let P=S∪{r}P = S \cup \{r\}. For t≥0t \ge 0, let GtG_t be the graph on PP with an edge {u,v}\{u, v\} whenever d(u,v)≤td(u, v) \le t. For i∈Si \in S, let Kt(i)K_t(i) be the component of GtG_t that contains ii. Let OPT(S)\mathrm{OPT}(S) be the cost of a cheapest connected subgraph of GG that contains PP, and let MST(S)\mathrm{MST}(S) be the cost of a minimum spanning tree of the complete graph on PP with costs dd.

The algorithm (lines L1 to L7) computes dd on PP, sorts the pairs of PP by dd, and scans them in this order. When a pair {u,v}\{u, v\} joins two components, line L5 adds (d(u,v)−t)/∣K∣(d(u, v) - t)/|K| to the share of each member of each component KK that does not contain rr, and line L6 sets t←d(u,v)t \leftarrow d(u, v) and merges the two components.

Lemma 1 (the shares as an integral). For every i∈Si \in S, the algorithm returns

ξ(i,S)=∫0∞[ r∉Kt(i) ]∣Kt(i)∣ dt,\xi(i, S) = \int_0^\infty \frac{[\, r \notin K_t(i) \,]}{|K_t(i)|}\, dt,

where [⋅][\cdot] is 1 if the condition holds and 0 otherwise.

Proof. The scan is Kruskal's algorithm on the complete graph on PP. Let w1≤w2≤⋯≤wkw_1 \le w_2 \le \cdots \le w_{k} be the costs of the kk pairs that merge two components, in scan order (∣P∣=k+1|P| = k + 1 points need kk merges). Set w0=0w_0 = 0. After the scan has processed every pair of cost at most tt, the union-find components are the components of GtG_t. A pair that is scanned between two merges does not merge anything. So for wj≤t<wj+1w_j \le t < w_{j+1}, the components of GtG_t are the components after the first jj merges. The step of line L5 for merge j+1j + 1 adds, to each ii in a component KK without rr, exactly the integral of 1/∣K∣1/|K| over [wj,wj+1)[w_j, w_{j+1}), since t=wjt = w_j at that moment. Equal costs give intervals of length 0, which add nothing. After the last merge all points are in the component of rr, and the integrand is 0. □\square

Lemma 2 (the sum). ∑i∈Sξ(i,S)=MST(S)\sum_{i \in S} \xi(i, S) = \mathrm{MST}(S).

Proof. Each component KK of GtG_t without rr contributes ∣K∣⋅1/∣K∣=1|K| \cdot 1/|K| = 1 to the integrand of the sum. So the sum is ∫0∞(κ(t)−1) dt\int_0^\infty (\kappa(t) - 1)\, dt, where κ(t)\kappa(t) is the number of components of GtG_t. With the merge costs w1,…,wkw_1, \ldots, w_k of Lemma 1, κ(t)−1=k−∣{j:wj≤t}∣=∣{j:wj>t}∣\kappa(t) - 1 = k - |\{ j : w_j \le t \}| = |\{ j : w_j > t \}|. So the sum is ∑j∫0∞[ wj>t ] dt=∑jwj\sum_j \int_0^\infty [\, w_j > t \,]\, dt = \sum_j w_j, the cost of the tree that Kruskal's algorithm builds, which is MST(S)\mathrm{MST}(S). □\square

Lemma 3 (budget). OPT(S)≤MST(S)≤2 OPT(S)\mathrm{OPT}(S) \le \mathrm{MST}(S) \le 2\, \mathrm{OPT}(S).

Proof. Lower bound: replace each edge {u,v}\{u, v\} of a minimum spanning tree on PP by a shortest path from uu to vv in GG. The union of these paths is a connected subgraph of GG that contains PP, and its cost is at most the sum of the path costs, MST(S)\mathrm{MST}(S). So OPT(S)≤MST(S)\mathrm{OPT}(S) \le \mathrm{MST}(S).

Upper bound: let T∗T^* be an optimal Steiner tree. Double each edge of T∗T^*. Every vertex then has even degree, so there is a closed walk that uses each doubled edge once, with cost 2 OPT(S)2\, \mathrm{OPT}(S). The walk visits every point of PP. List the points of PP in the order of their first visit, p0,p1,…,pkp_0, p_1, \ldots, p_k. The part of the walk from pj−1p_{j-1} to pjp_j costs at least d(pj−1,pj)d(p_{j-1}, p_j), so the path p0,p1,…,pkp_0, p_1, \ldots, p_k in the complete graph on PP costs at most 2 OPT(S)2\, \mathrm{OPT}(S). It is a spanning tree of PP, so MST(S)≤2 OPT(S)\mathrm{MST}(S) \le 2\, \mathrm{OPT}(S). □\square

By Lemmas 2 and 3, the shares satisfy OPT(S)≤∑i∈Sξ(i,S)≤2 OPT(S)\mathrm{OPT}(S) \le \sum_{i \in S} \xi(i, S) \le 2\, \mathrm{OPT}(S). The method is 2-budget balanced in the form C(S)≤∑iξ(i,S)≤β C(S)C(S) \le \sum_i \xi(i, S) \le \beta\, C(S) with C=OPTC = \mathrm{OPT} and β=2\beta = 2. It is exactly budget balanced for the cost of the tree it builds, when the tree is taken as the minimum spanning tree on PP with the costs dd.

Lemma 4 (cross-monotonicity). If i∈S⊆S′i \in S \subseteq S' and r∉S′r \notin S', then ξ(i,S′)≤ξ(i,S)\xi(i, S') \le \xi(i, S).

Proof. The metric dd does not depend on the terminal set. So GtG_t for SS is the subgraph of GtG_t for S′S' induced by S∪{r}S \cup \{r\}. A path in the smaller graph is a path in the larger one, so Kt(i)⊆Kt′(i)K_t(i) \subseteq K'_t(i), where Kt′(i)K'_t(i) is the component of ii for S′S'. Hence ∣Kt′(i)∣≥∣Kt(i)∣|K'_t(i)| \ge |K_t(i)|, and if r∈Kt(i)r \in K_t(i) then r∈Kt′(i)r \in K'_t(i). So the integrand of Lemma 1 for S′S' is at most the integrand for SS at every tt, and the integral is at most the integral for SS. □\square

Lemma 5 (agreement with the primal-dual algorithm). Consider the complete directed graph on PP with arc costs d(u,v)d(u, v). The primal-dual algorithm keeps a dual value yX≥0y_X \ge 0 for each set X⊆P∖{r}X \subseteq P \setminus \{r\}. The load of an arc (u,v)(u, v) is the sum of yXy_X over the sets XX with v∈Xv \in X and u∉Xu \notin X, and the arc is tight when its load equals d(u,v)d(u, v). A set is active if it is a strongly connected component of the tight arcs, does not contain rr, and has no tight arc that enters it. Each active set raises its dual at rate 1 and splits the increase equally among its members. Then at every time tt the active sets are the components of GtG_t without rr, so each terminal is charged at rate [ r∉Kt(i) ]/∣Kt(i)∣[\, r \notin K_t(i) \,]/|K_t(i)|, and the shares equal those of Lemma 1.

Proof. For v∈P∖{r}v \in P \setminus \{r\}, let τ(v)\tau(v) be the first time at which vv is in the component of rr in GtG_t. We show by induction over time the following claim: for every tt, the active sets are the components of GtG_t without rr, and an arc (u,v)(u, v) with u∉Kt(v)u \notin K_t(v) has load min⁡(t,τ(v))\min(t, \tau(v)). At t=0t = 0 no dual is positive, every load is 0, and an arc is tight only if d(u,v)=0d(u, v) = 0, in which case uu and vv are in one component of G0G_0.

Assume the claim up to time tt. An arc (u,v)(u, v) between two components of GtG_t has load min⁡(t,τ(v))\min(t, \tau(v)). If it were tight, then d(u,v)≤td(u, v) \le t, and uu and vv would be in one component of GtG_t. So no arc between components is tight. Inside a component KK without rr, each merge that built KK was caused by a pair {u,v}\{u, v\} with d(u,v)d(u, v) equal to the merge time ss, and at time ss both sides were components without rr. By the claim, both arcs (u,v)(u, v) and (v,u)(v, u) had load s=d(u,v)s = d(u, v) and became tight. These pairs form a spanning tree of KK, so the tight arcs inside KK are strongly connected. So KK is a strongly connected component of the tight arcs, it has no tight arc that enters it, and it does not contain rr: KK is active. Inside the component of rr, the same argument shows that each merge made the arc from the side of rr into the other side tight. So every point of this component is reached from rr by tight arcs, and every strongly connected component in it other than the one of rr has a tight arc that enters it. So no set inside the component of rr is active.

So the active sets are exactly the components of GtG_t without rr. They are disjoint, so the load of an arc (u,v)(u, v) with u∉Kt(v)u \notin K_t(v) grows at rate 1 while Kt(v)K_t(v) does not contain rr and at rate 0 after that. This keeps the load equal to min⁡(t,τ(v))\min(t, \tau(v)). The components of GtG_t change only at the costs d(u,v)d(u, v), and at each such time the argument above applies again. □\square

Cost. Line L1 runs Floyd-Warshall in O(N3)O(N^3) time, or Dijkstra's algorithm from each of the k+1k + 1 points of PP. Line L2 sorts O(k2)O(k^2) pairs in O(k2log⁡k)O(k^2 \log k) time. There are kk merges. Each merge runs line L5 over all k+1k + 1 points and relabels the smaller component, so lines L4 to L6 take O(k2)O(k^2) time in total, plus O(k2)O(k^2) for the pairs that do not merge. The total time is O(N3+k2log⁡k)O(N^3 + k^2 \log k), and the extra space is O(N2)O(N^2) for the metric.

Remark. The tests in impl/python/test_jain_vazirani_steiner_cost_sharing.py compare the shares on 250 random graphs with at most 7 vertices against an event-by-event simulation of the primal-dual algorithm of Lemma 5, check Lemma 2 against Prim's algorithm on the metric closure, check Lemma 3 against an optimal Steiner tree found by brute force over the sets of Steiner vertices, and check Lemma 4 for every pair of nested terminal sets on 60 random graphs. ■\blacksquare

Complexity

Line L1 takes O(N3)O(N^3) time with Floyd-Warshall, or k+1k + 1 runs of Dijkstra's algorithm on a sparse graph. Line L2 sorts O(k2)O(k^2) pairs in O(k2log⁡k)O(k^2 \log k) time. There are kk merges, and each runs line L5 in O(k)O(k) time, so lines L3 to L6 take O(k2)O(k^2) time. The total is O(N3+k2log⁡k)O(N^3 + k^2 \log k) time with O(N2)O(N^2) space for the metric. When the method runs inside the Moulin mechanism, the metric is computed once, and each round costs O(k2log⁡k)O(k^2 \log k), so the mechanism takes O(N3+k3log⁡k)O(N^3 + k^3 \log k) time.

Properties

  • Cross-monotonic, so the Moulin mechanism built on it is group strategyproof, with no positive transfers, voluntary participation and consumer sovereignty.
  • 2-budget balanced with respect to the optimal Steiner tree cost, and exactly budget balanced for the minimum spanning tree on PP that the mechanism builds.
  • Deterministic and exact. With rational costs the shares are rational. Ties among pair costs do not change the shares, because they give intervals of length zero.
  • Symmetric inside a component. Terminals in the same component at all times pay the same.
  • Not efficient. Roughgarden and Sundararajan (2009) showed that the Moulin mechanism with these shares has social cost within a factor O(log⁡2k)O(\log^2 k) of the optimum, and that every Moulin mechanism for Steiner tree with constant budget balance has social cost Ω(log⁡2k)\Omega(\log^2 k) times the optimum on some inputs.

Variants and improvements

  • Spanning tree games. In a minimum cost spanning tree game whose costs already satisfy the triangle inequality, the metric closure changes no cost. Then the shares of a coalition sum to exactly its minimum spanning tree cost, and they never rise when a player joins, which Bird's rule does not guarantee. Without the triangle inequality, a coalition in the closure may route through other players' vertices, and the shares are budget balanced only for the closure.
  • Steiner forest. For pairs of terminals that must be connected, without a common root, the Goemans-Williamson primal-dual algorithm is a 2-approximation. Its natural shares are not cross-monotonic. Könemann, Leonardi, Schäfer and van Zwam (2008) gave a group strategyproof mechanism for Steiner forest with a constant budget balance factor, based on a stronger relaxation.
  • Facility location. The facility location algorithm of Jain and Vazirani is a different primal-dual algorithm by the same authors, for a different problem. Later work turned primal-dual algorithms for facility location into cross-monotonic methods as well.
  • Halved shares. Dividing every share by 2 gives the form used by Jain and Vazirani: the shares never exceed the optimal cost, so no set of terminals is overcharged, and they recover at least half the cost of the tree that is built.

When to use it

Use these shares when a network with a root, such as a multicast tree, is offered to users with private values, the users must pay for the network, and the mechanism must resist collusion. The Moulin mechanism with these shares is group strategyproof and covers the cost of the tree it builds. Use the spanning tree on the metric closure as the network, or prune it to a cheaper Steiner tree and accept a surplus. Do not use it when the operator needs exact budget balance for the optimal tree, which is impossible in polynomial time unless P = NP, or when the efficiency loss of a factor log⁡2k\log^2 k is too large.

Pitfalls

  • Charging the edges of GG instead of the closure. The method works on the shortest path metric between terminals and the root. Steiner vertices are not players and pay nothing. Running the clock on the edges of GG itself would charge for edges that the tree does not need.
  • Two forms of budget balance. The shares here cover the cost of the spanning tree on PP and are at most twice the optimum. Papers that use the other form divide them by 2. Mixing the two forms changes every stated factor by 2.
  • Overcharging the built network. In the example, the shares sum to 10, but the network in GG that the spanning tree maps to costs only 8. A mechanism that builds the pruned network collects a surplus. This does not break group strategyproofness.
  • Shares that depend on the order of ties. The shares do not depend on how ties among pair costs are broken, but the tree does. Do not report the tree as unique.
  • Inexact arithmetic. The Moulin mechanism compares bids with shares. Shares with denominators such as 1/61/6 cannot be stored exactly in floating point. Use rationals.

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.

jain_vazirani_steiner_cost_sharing.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jain-vazirani-steiner-cost-sharing/. The authors are listed in prov/F0QV3E.jsonl.
"""Jain-Vazirani cost sharing for Steiner trees, in its threshold form.

The input is an undirected graph with nonnegative edge costs, a root r and a set S of
terminals (the players). Let d be the shortest path metric of the graph. Grow a time t from 0.
At time t, two points of S + {r} are joined when d(u, v) <= t. While the component of a
terminal does not contain the root, the terminal pays 1/|K| per unit of time, where K is its
component. The shares add up to the cost of a minimum spanning tree on S + {r} under d. This
is at least the optimal Steiner tree cost and at most twice it, and no share rises when S grows.

The same shares come out of the primal-dual algorithm of Jain and Vazirani (2001) on the
bidirected metric closure, where each active component raises its dual at rate 1 and splits
the increase equally among its terminals.
"""

from fractions import Fraction
from itertools import combinations


def metric_closure(n, edges):
    """All-pairs shortest path costs by Floyd-Warshall; None means unreachable."""
    d = [[None] * n for _ in range(n)]
    for v in range(n):
        d[v][v] = Fraction(0)
    for u, v, w in edges:
        w = Fraction(w)
        if d[u][v] is None or w < d[u][v]:
            d[u][v] = d[v][u] = w
    for k in range(n):
        dk = d[k]
        for i in range(n):
            dik = d[i][k]
            if dik is None:
                continue
            di = d[i]
            for j in range(n):
                if dk[j] is not None and (di[j] is None or dik + dk[j] < di[j]):
                    di[j] = dik + dk[j]
    return d


def _check(n, edges, root, terminals):
    if not 0 <= root < n:
        raise ValueError("root out of range")
    for u, v, w in edges:
        if not (0 <= u < n and 0 <= v < n):
            raise ValueError("edge end out of range")
        if w < 0:
            raise ValueError("negative edge cost")
    terms = sorted(set(terminals))
    for i in terms:
        if not 0 <= i < n:
            raise ValueError("terminal out of range")
        if i == root:
            raise ValueError("the root is not a player")
    return terms


def jv_cost_shares(n, edges, root, terminals):
    """Return {terminal: share} as Fractions. Vertices are 0 .. n-1; edges are (u, v, cost)."""
    terminals = _check(n, edges, root, terminals)
    d = metric_closure(n, edges)  # @line L1
    points = [root] + terminals
    for p in terminals:
        if d[root][p] is None:
            raise ValueError("terminal not connected to the root")
    pairs = sorted((d[u][v], u, v) for u, v in combinations(points, 2))  # @line L2
    comp = {p: p for p in points}
    members = {p: [p] for p in points}
    share = {i: Fraction(0) for i in terminals}
    t = Fraction(0)  # @line L3
    for w, u, v in pairs:  # @line L4
        cu, cv = comp[u], comp[v]
        if cu == cv:
            continue
        for c, mem in members.items():  # @line L5
            if c != comp[root]:
                for i in mem:
                    share[i] += (w - t) / len(mem)
        t = w  # @line L6
        if len(members[cu]) < len(members[cv]):
            cu, cv = cv, cu
        for p in members[cv]:
            comp[p] = cu
        members[cu].extend(members.pop(cv))
    return share  # @line L7


def mst_cost(d, points):
    """Cost of a minimum spanning tree on points under the metric d (Prim, O(k^2))."""
    points = list(points)
    if len(points) <= 1:
        return Fraction(0)
    best = {p: d[points[0]][p] for p in points[1:]}
    total = Fraction(0)
    while best:
        p = min(best, key=lambda q: (best[q], q))
        total += best.pop(p)
        for q in best:
            if d[p][q] < best[q]:
                best[q] = d[p][q]
    return total
test_jain_vazirani_steiner_cost_sharing.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/jain-vazirani-steiner-cost-sharing/. The authors are listed in prov/F0QV3E.jsonl.
"""Tests for jain_vazirani_steiner_cost_sharing: the worked example, edge cases, and random
graphs checked against an independent simulation of the directed primal-dual algorithm, the
MST of the metric closure, a brute-force optimal Steiner tree, and cross-monotonicity."""

import random
import unittest
from fractions import Fraction as F
from itertools import combinations

from jain_vazirani_steiner_cost_sharing import jv_cost_shares, metric_closure, mst_cost

# Root 0, terminals 1 (a), 2 (b), 3 (c), Steiner vertex 4 (s).
EXAMPLE = [(0, 4, 4), (4, 1, 1), (4, 2, 1), (4, 3, 2), (0, 3, 5)]


def primal_dual_oracle(d, root, terminals):
    """Event-by-event simulation of the primal-dual algorithm on the bidirected closure.

    Each arc (u, v) has a load: the sum of the duals of the sets that contain v but not u.
    An arc is tight when its load equals d(u, v). The active sets are the strongly connected
    components of the tight arcs that do not contain the root and have no tight arc entering
    them. Each active set raises its dual at rate 1 and splits it equally among its members."""
    pts = [root] + sorted(terminals)
    arcs = [(u, v) for u in pts for v in pts if u != v]
    load = {a: F(0) for a in arcs}
    tight = {a for a in arcs if d[a[0]][a[1]] == 0}
    share = {i: F(0) for i in terminals}
    while True:
        reach = {u: {u} for u in pts}
        changed = True
        while changed:
            changed = False
            for u, v in tight:
                for x in pts:
                    if u in reach[x] and not reach[v] <= reach[x]:
                        reach[x] |= reach[v]
                        changed = True
        sccs = {frozenset(y for y in reach[x] if x in reach[y]) for x in pts}
        active = [C for C in sccs if root not in C
                  and not any(u not in C and v in C for u, v in tight)]
        if not active:
            return share
        growing = [(u, v) for C in active for (u, v) in arcs if v in C and u not in C]
        dt = min(d[u][v] - load[(u, v)] for u, v in growing)
        for C in active:
            for i in C:
                share[i] += dt / len(C)
        for a in growing:
            load[a] += dt
            if load[a] == d[a[0]][a[1]]:
                tight.add(a)


def steiner_opt(d, n, root, terminals):
    """Optimal Steiner tree cost: the best MST over terminals, root and a set of other vertices."""
    others = [v for v in range(n) if v != root and v not in terminals]
    best = None
    for k in range(len(others) + 1):
        for extra in combinations(others, k):
            c = mst_cost(d, [root] + list(terminals) + list(extra))
            if best is None or c < best:
                best = c
    return best


def random_graph(rng, n):
    edges = []
    for v in range(1, n):
        edges.append((rng.randrange(v), v, rng.randint(1, 9)))
    for u, v in combinations(range(n), 2):
        if rng.random() < 0.35:
            edges.append((u, v, rng.randint(1, 9)))
    return edges


class TestJainVazirani(unittest.TestCase):
    def test_worked_example(self):
        shares = jv_cost_shares(5, EXAMPLE, 0, [1, 2, 3])
        self.assertEqual(shares, {1: F(19, 6), 2: F(19, 6), 3: F(11, 3)})
        d = metric_closure(5, EXAMPLE)
        self.assertEqual(sum(shares.values()), 10)
        self.assertEqual(mst_cost(d, [0, 1, 2, 3]), 10)
        self.assertEqual(steiner_opt(d, 5, 0, [1, 2, 3]), 8)
        self.assertEqual(jv_cost_shares(5, EXAMPLE, 0, [1, 2]), {1: F(7, 2), 2: F(7, 2)})
        self.assertEqual(jv_cost_shares(5, EXAMPLE, 0, [1, 3]), {1: F(4), 3: F(4)})
        for i in (1, 2, 3):
            self.assertEqual(jv_cost_shares(5, EXAMPLE, 0, [i]), {i: F(5)})

    def test_edge_cases(self):
        self.assertEqual(jv_cost_shares(1, [], 0, []), {})
        self.assertEqual(jv_cost_shares(2, [(0, 1, 3)], 0, [1, 1]), {1: F(3)})
        self.assertEqual(jv_cost_shares(3, [(0, 1, 0), (1, 2, 0)], 0, [1, 2]), {1: 0, 2: 0})
        with self.assertRaises(ValueError):
            jv_cost_shares(2, [(0, 1, 3)], 0, [0])
        with self.assertRaises(ValueError):
            jv_cost_shares(3, [(0, 1, 3)], 0, [2])
        with self.assertRaises(ValueError):
            jv_cost_shares(2, [(0, 1, -1)], 0, [1])
        with self.assertRaises(ValueError):
            jv_cost_shares(2, [(0, 1, 1)], 0, [5])

    def test_random_against_oracle_and_bounds(self):
        rng = random.Random(3)
        for _ in range(250):
            n = rng.randint(2, 7)
            edges = random_graph(rng, n)
            d = metric_closure(n, edges)
            root = rng.randrange(n)
            others = [v for v in range(n) if v != root]
            terms = sorted(rng.sample(others, rng.randint(1, len(others))))
            shares = jv_cost_shares(n, edges, root, terms)
            self.assertEqual(shares, primal_dual_oracle(d, root, terms))
            total = sum(shares.values())
            self.assertEqual(total, mst_cost(d, [root] + terms))
            opt = steiner_opt(d, n, root, terms)
            self.assertLessEqual(opt, total)
            self.assertLessEqual(total, 2 * opt)

    def test_cross_monotonic(self):
        rng = random.Random(4)
        for _ in range(60):
            n = rng.randint(3, 7)
            edges = random_graph(rng, n)
            terms = list(range(1, n))
            full = {}
            for k in range(1, len(terms) + 1):
                for S in combinations(terms, k):
                    full[S] = jv_cost_shares(n, edges, 0, S)
            for S, sh in full.items():
                for k in range(1, len(S)):
                    for T in combinations(S, k):
                        for i in T:
                            self.assertGreaterEqual(full[T][i], sh[i])

    def test_fractional_costs(self):
        edges = [(0, 1, F(1, 2)), (1, 2, F(1, 3)), (0, 2, F(5, 6))]
        shares = jv_cost_shares(3, edges, 0, [1, 2])
        self.assertEqual(sum(shares.values()), F(5, 6))
        self.assertEqual(shares, {1: F(1, 3) + F(1, 12), 2: F(1, 3) + F(1, 12)})


if __name__ == "__main__":
    unittest.main()

History

Moulin (1999) showed that a cross-monotonic cost-sharing method gives a group strategyproof mechanism, and Feigenbaum, Papadimitriou and Shenker (2001) studied the cost of multicast transmissions over a fixed tree from the point of view of computation. For Steiner trees exact budget balance is NP-hard, so Jain and Vazirani (2001) gave a cross-monotonic method with a budget balance factor of 2, read off from the dual of a primal-dual algorithm on the directed relaxation of Edmonds (1967). The paper started a line of work that turned primal-dual approximation algorithms into cost-sharing methods, for facility location, Steiner forest and other problems. Roughgarden and Sundararajan (2009) later measured the efficiency loss of these mechanisms and showed that the factor O(log⁡2k)O(\log^2 k) is the best possible for Moulin mechanisms for Steiner tree with constant budget balance.

References

  1. Applications of approximation algorithms to cooperative games, the cross-monotonic cost-sharing method for Steiner trees from a primal-dual algorithm, and the group strategyproof mechanism built on it
  2. Optimum branchings, minimum cost arborescences, the directed relaxation on which the dual growth is based
  3. Quantifying inefficiency in cost-sharing mechanisms, Tim Roughgarden and Mukund Sundararajan, Journal of the ACM 56(4), Article 23, 2009, the O(log^2 k) social cost bound for the Jain-Vazirani mechanism and the matching lower bound for Moulin mechanisms for Steiner tree with constant budget balance
  4. Noam Nisan, Tim Roughgarden, Eva Tardos and Vijay V. Vazirani (eds.), Algorithmic Game Theory, Cambridge University Press, 2007, Chapter 15 (Kamal Jain and Mohammad Mahdian, Cost Sharing), on cross-monotonic cost-sharing methods and the Moulin mechanism

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
  • a scene preset for the example