1"""Functions for computing an approximate minimum weight vertex cover.
2
3A |vertex cover|_ is a subset of nodes such that each edge in the graph
4is incident to at least one node in the subset.
5
6.. _vertex cover: https://en.wikipedia.org/wiki/Vertex_cover
7.. |vertex cover| replace:: *vertex cover*
8
9"""
10
11import networkx as nx
12
13__all__ = ["min_weighted_vertex_cover"]
14
15
16@nx._dispatchable(node_attrs="weight")
17def min_weighted_vertex_cover(G, weight=None):
18 r"""Returns an approximate minimum weighted vertex cover.
19
20 The set of nodes returned by this function is guaranteed to be a
21 vertex cover, and the total weight of the set is guaranteed to be at
22 most twice the total weight of the minimum weight vertex cover. In
23 other words,
24
25 .. math::
26
27 w(S) \leq 2 * w(S^*),
28
29 where $S$ is the vertex cover returned by this function,
30 $S^*$ is the vertex cover of minimum weight out of all vertex
31 covers of the graph, and $w$ is the function that computes the
32 sum of the weights of each node in that given set.
33
34 Parameters
35 ----------
36 G : NetworkX graph
37
38 weight : string, optional (default = None)
39 If None, every node has weight 1. If a string, use this node
40 attribute as the node weight. A node without this attribute is
41 assumed to have weight 1.
42
43 Returns
44 -------
45 min_weighted_cover : set
46 Returns a set of nodes whose weight sum is no more than twice
47 the weight sum of the minimum weight vertex cover.
48
49 Notes
50 -----
51 For a directed graph, a vertex cover has the same definition: a set
52 of nodes such that each edge in the graph is incident to at least
53 one node in the set. Whether the node is the head or tail of the
54 directed edge is ignored.
55
56 This is the local-ratio algorithm for computing an approximate
57 vertex cover. The algorithm greedily reduces the costs over edges,
58 iteratively building a cover. The worst-case runtime of this
59 implementation is $O(m \log n)$, where $n$ is the number
60 of nodes and $m$ the number of edges in the graph.
61
62 References
63 ----------
64 .. [1] Bar-Yehuda, R., and Even, S. (1985). "A local-ratio theorem for
65 approximating the weighted vertex cover problem."
66 *Annals of Discrete Mathematics*, 25, 27–46
67 <http://www.cs.technion.ac.il/~reuven/PDF/vc_lr.pdf>
68
69 """
70 cost = dict(G.nodes(data=weight, default=1))
71 # While there are uncovered edges, choose an uncovered and update
72 # the cost of the remaining edges.
73 cover = set()
74 for u, v in G.edges():
75 if u in cover or v in cover:
76 continue
77 if cost[u] <= cost[v]:
78 cover.add(u)
79 cost[v] -= cost[u]
80 else:
81 cover.add(v)
82 cost[u] -= cost[v]
83 return cover