vertex_cover.py 2.7 KB

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